package com.pureut.storage.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pureut.storage.domain.*;
import com.pureut.storage.domain.system.domain.SysDocument;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.PurchaseReceiptExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.util.UnitUtil;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.utils.VariousKeyEnum;
import com.pureut.storage.vo.*;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.domain.R;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.redis.utils.RedisUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.goods.api.RemoteGoodsDisburseService;
import com.sale.goods.api.RemoteGoodsPaymentService;
import com.sale.goods.api.dto.ImparityGoodsDto;
import com.sale.goods.api.vo.GetDataByCodeGoodsVo;
import com.sale.order.api.RemotePurchaseOrderService;
import com.sale.order.api.vo.PurchaseOrderTraceVo;
import com.sale.order.api.vo.UpdatePurchaseOrderDataVo;
import com.sale.storage.api.dto.PurchaseOrderTrackDto;
import com.sale.storage.api.vo.QuantityDataVo;
import com.sale.storage.api.vo.UpdateInvoicedQuantityVo;
import com.sale.system.api.*;
import com.sale.system.api.domain.SysAuxiliary;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.SysUser;
import com.sale.system.api.domain.dto.SysApiCategoryDto;
import com.sale.system.api.domain.dto.SysAuxiliaryUnitDateDetailResultDto;
import com.sale.system.api.domain.dto.SysDocumentResultDto;
import com.sale.system.api.domain.dto.SysMaterialCodingResultDto;
import com.sale.system.api.model.MaterialUnitDto;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/***
 * 采购入库实现层
 * Author:C
 * Date:2022/12/23 10:14
 * @DESC
 */
@Service
@RequiredArgsConstructor
public class PurchaseReceiptServiceImpl implements PurchaseReceiptService {


    private final PurchaseReceiptMapper purchaseReceiptMapper;

    private final WarehouseService warehouseService;

    private final PurchaseReceiptDetailMapper purchaseReceiptDetailMapper;

    private final WmsStockInfoMapper wmsStockInfoMapper;

    private final StockOutInfoMapper stockOutInfoMapper;

    private final CheckManagementMapper checkManagementMapper;

    private final AllotManagementMapper allotManagementMapper;

    @Resource
    WipCompletionMapper wipCompletionMapper;


    @Resource
    SalesReturnMapper salesReturnMapper;


    @Resource
    SalesReturnService salesReturnService;


    @Resource
    WipCompletionService wipCompletionService;


    //销售发货
    @Resource
    PickingSaleMapper pickingSaleMapper;

    @Resource
    PickingSaleService pickingSaleService;

    //采购退货
    @Resource
    PickingPurchaseMapper pickingPurchaseMapper;

    @Resource
    PickingPurchaseService pickingPurchaseService;

    //其他出库
    @Resource
    PickingRestMapper pickingRestMapper;

    @Resource
    PickingRestService pickingRestService;

    @Resource
    StockOutInfoService stockOutInfoService;

    @Resource
    AllotManagementService allotManagementService;

    @Resource
    IncomingMaterialPrintingDetailMapper incomingMaterialPrintingDetailMapper;

    @Resource
    IncomingMaterialPrintingMapper incomingMaterialPrintingMapper;

    @DubboReference
    RemoteCodeService remoteCodeService;

    @DubboReference
    RemoteSysSupplierService remoteSysSupplierService;

    @DubboReference
    RemoteUnitService remoteUnitService;

    @DubboReference
    RemoteMenuService remoteMenuService;

    @DubboReference
    RemoteDocumentService remoteDocumentService;

    @DubboReference
    RemoteUserService remoteUserService;

    @DubboReference
    RemoteCodingService remoteCodingService;

    @DubboReference
    RemoteGoodsDisburseService remoteGoodsDisburseService;

    @DubboReference
    RemoteInventoryInquiryService remoteInventoryInquiryService;

    @Resource
    IncomingMaterialPrintingDetailService incomingMaterialPrintingDetailService;

    @Resource
    UnitUtil unitUtil;

    @Resource
    PublicMaterialMapper publicMaterialMapper;

    @Resource
    ProductionMaterialReturnMapper productionMaterialReturnMapper;

    @Resource
    SubcontractReceiptMapper subcontractReceiptMapper;

    @Resource
    MiscellaneousReceiptMapper miscellaneousReceiptMapper;

    //反攻出库
    @Resource
    PickingCompleteService pickingCompleteService;

    //委外退货
    @Resource
    PickingReturnsService pickingReturnsService;

    //委外发货
    @Resource
    PickingOutsourceService pickingOutsourceService;

    //委外发货
    @Resource
    PickingOutsourceMapper pickingOutsourceMapper;

    @Resource
    ProductionMaterialReturnService productionMaterialReturnService;

    @Resource
    MiscellaneousReceiptService miscellaneousReceiptService;

    //返工出库
    @Resource
    PickingCompleteMapper pickingCompleteMapper;

    //委外退货
    @Resource
    PickingReturnsMapper pickingReturnsMapper;

    /**
     * 获取采购入库列表
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    public TableDataInfo<PurchaseReceiptDto> getReceiptList(PurchaseReceiptVo purchaseReceiptVo, PageQuery pageQuery) throws Exception {
        Page<PurchaseReceiptDto> receiptList = purchaseReceiptMapper.getReceiptList(pageQuery.build(), purchaseReceiptVo);
        List<PurchaseReceiptDto> records = receiptList.getRecords();
        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();
        //状态
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "purchase_receipt_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //收发类型
        List<SysDictData> rdArray = CacheUtils.get(CacheNames.SYS_DICT, "purchase_receipt_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //供应商
        Map<String, String> supplierMap = remoteSysSupplierService.getOpenSupplierFinance();

        for (PurchaseReceiptDto entity : records) {

            //收发类型
            entity.setReceiveTypeDict(rdMap.get(entity.getReceiveType()));
            //供应商
            entity.setSupplierName(supplierMap.get(entity.getSupplierCode()));
            //辅助属性
            List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
            entity.setAuxiliaryAttribute(statsArray);
            //采购入库状态字典值
            entity.setStatus(entity.getStatus());
            entity.setStatusDict(statusMap.get(entity.getStatus()));
            //物料单位
            if (entity.getMaterialUnit() != null) {
                entity.setUnitDict(unitByCodeToMap.get(entity.getMaterialUnit()).getUnitName());
            }
            //如果该物料配置了多单位，就进行单位转换
//            if (entity.getMaterialMoreUnit() != null) {
//                //转换
//                UnitConversionDto unitConversionDto = unitUtil.atWillunitConversion(entity.getMaterialUnit(), entity.getMaterialCode(),
//                    String.valueOf(entity.getPlannedWeight()), entity.getMaterialId());
//                if (unitConversionDto != null) {
//                    entity.setUnitConversion(unitConversionDto.getMaterialMoreUnitNumber());
//                }
//            }
            //单位转换
            String s = unitUtil.unitC(entity.getMaterialCode(),
                String.valueOf(entity.getPlannedWeight()),
                entity.getMaterialId(),
                unitByCodeToMap.get(entity.getMaterialUnit()).getUnitName());
            entity.setUnitConversion(s);


            //单据类型
            entity.setDocumentType(entity.getDocumentType());
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(entity.getDocumentType())));

            //生成方式
            entity.setGenerationMethod(entity.getGenerationMethod());
            entity.setGenerationMethodDict(GenerationMethodEnum.getValue(Integer.parseInt(entity.getGenerationMethod())));

            //类别
            if (entity.getMaterialCategory() == 1) {
                entity.setMaterialCategoryDict("原料");
            } else {
                entity.setMaterialCategoryDict("成品");
            }
        }
        return TableDataInfo.build(receiptList);
    }

    /**
     * 新增
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addReceipt(PurchaseReceiptVo purchaseReceiptVo) throws Exception {

        List<PurchaseVo> procurementList = purchaseReceiptVo.getProcurementList();
        List<PurchaseReceipt> purchaseReceiptArrayList = new ArrayList<>();
        if (procurementList.size() > 0) {
            for (PurchaseVo entity : procurementList) {
                PurchaseReceipt purchaseReceipt = new PurchaseReceipt();
                String authorityCoding = remoteCodeService.authorityCoding("warehouse:warehousing:purchase:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                purchaseReceipt.setReceiptNo(authorityCoding)
                    .setDeptId(LoginHelper.getDeptId())
                    .setStatus(1)
                    .setCreateTime(new Date())
                    .setPurchaseOrderNo(entity.getPurchaseOrderNo())
                    .setMaterialCode(entity.getMaterialCode())
                    .setMaterialCategory(entity.getMaterialCategory())
                    .setPlannedWeight(entity.getPlannedWeight())
                    .setWarehousingWarehouse(Long.parseLong(entity.getWarehousingWarehouse()))
                    .setSupplierCode(purchaseReceiptVo.getSupplierCode())
                    .setEstimatedTime(purchaseReceiptVo.getEstimatedTime())
                    .setDrawerTime(new Date())
                    .setRemark(purchaseReceiptVo.getRemark())
                    .setDrawerBy(LoginHelper.getUsername())
                    .setMaterialUnit(entity.getMaterialUnit())
                    .setReceiveType(purchaseReceiptVo.getReceiveType())
                    .setDocumentType(DocumentTypeEnum.PURCHASE_RECEIPT.getCode())
//                    .setUnitPrice(new BigDecimal(entity.getUnitPrice()))
                    .setGenerationMethod(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
                purchaseReceiptArrayList.add(purchaseReceipt);
            }
            return purchaseReceiptMapper.insertBatch(purchaseReceiptArrayList);
        } else {
            throw new GlobalException("请至少选择一条数据");
        }
    }

    /**
     * 批次到货新增
     *
     * @param purchaseOrderDto
     * @return
     */
    @Override
    public boolean batchArrival(PurchaseOrderDto purchaseOrderDto) throws Exception {
        List<MaterialVo> materialList = purchaseOrderDto.getMaterialList();
        PurchaseReceipt purchaseReceipt = new PurchaseReceipt();
        for (MaterialVo entity : materialList) {
            String authorityCoding = remoteCodeService.authorityCoding("warehouse:purchase:list");
            if (authorityCoding == null) {
                throw new GlobalException("该单据未进行配置，无法生成单据编码");
            }
            purchaseReceipt.setReceiptNo(authorityCoding)
                .setDeptId(LoginHelper.getDeptId())
//                .setPlannedWeight(purchaseOrderDto.getMaterialList().get(0).getActualWeight())
                .setPlannedWeight(Double.parseDouble(entity.getArrivalNumber()))
                .setStatus(1)
                .setPurchaseOrderNo(purchaseOrderDto.getPurchaseOrderNo())
                .setMaterialId(entity.getMaterialId())
                .setMaterialCode(entity.getMaterialCode())
                .setUnitPrice(BigDecimal.valueOf(Double.parseDouble(entity.getActualUnitPrice())))
                .setMaterialCategory(Integer.parseInt(purchaseOrderDto.getMaterialCategory()))
                .setSupplierCode(purchaseOrderDto.getSupplierCode())
                .setEstimatedTime(purchaseOrderDto.getEstimatedTime())
                .setDrawerBy(LoginHelper.getUsername())
                .setDrawerTime(new Date())
                .setMaterialUnit(entity.getUnit())
                .setTenantId(RedisUtils.getCacheObject(LoginHelper.getUserIdStr()))
                .setCreateTime(new Date())
                .setDocumentType(DocumentTypeEnum.PURCHASE_RECEIPT.getCode())
                .setContractNumber(purchaseOrderDto.getPurchaseContractNo())
                .setArrivalNumber(Integer.parseInt(entity.getArrivalNumber()))
                .setGenerationMethod(GenerationMethodEnum.AUTO_GENERATE.getCode());
        }
        return purchaseReceiptMapper.insert(purchaseReceipt) > 0;
    }

    /**
     * 关结
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean close(PurchaseReceiptVo purchaseReceiptVo) {
        PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(purchaseReceiptVo.getId());
        //已完成、已关结不可重复关结；
        if (purchaseReceipt.getStatus() != 5 && purchaseReceipt.getStatus() != 4) {
            //1、关结时判断对应的入库单是否关联了未完成的来料打印单，若存在未完成的来料打印单，则提示"存在未完成的来料打印单,不能关结"
            List<IncomingMaterialPrinting> incomingMaterialPrintings = incomingMaterialPrintingMapper.selectList(
                new QueryWrapper<IncomingMaterialPrinting>()
                    .lambda().eq(IncomingMaterialPrinting::getReceiptNo, purchaseReceipt.getReceiptNo()));
            for (IncomingMaterialPrinting entity : incomingMaterialPrintings) {
                if (entity.getPrintStatus() == 1) {
                    throw new GlobalException("存在未完成的来料打印单,不能关结");
                }
            }
            //2、入库中的单据关结后，单据状态变为“已关结”，生成的物料号码状态为未入库的删除同时删除库存中的物料号码
            if (purchaseReceipt.getStatus() == 2) {
                List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(
                    new QueryWrapper<PurchaseReceiptDetail>()
                        .lambda().eq(PurchaseReceiptDetail::getReceiptId, purchaseReceipt.getId()));

                purchaseReceipt.setStatus(4)
                    .setCloseReason(purchaseReceiptVo.getCloseReason())
                    .setClosingBy(LoginHelper.getUsername())
                    .setClosingTime(new Date());
                //获取待入库的明细数据物料号码
                List<String> collect1 = purchaseReceiptDetailList.stream().filter(a -> a.getStatus() == 1)
                    .map(PurchaseReceiptDetail::getMaterialNumber).collect(Collectors.toList());
                //获取物料号码状态为未入库的数据，进行删除
                List<PurchaseReceiptDetail> collect = purchaseReceiptDetailList.stream().filter(a -> a.getStatus() == 1)
                    .collect(Collectors.toList());
                //获取已经扫码的数据，状态修改为已入库
                List<PurchaseReceiptDetail> collect2 = purchaseReceiptDetailList.stream().filter(a -> a.getStatus() != 1)
                    .collect(Collectors.toList());
                if (collect2.size() > 0) {
                    for (PurchaseReceiptDetail entity : collect2) {
                        entity.setStatus(3);
                    }
                    purchaseReceiptDetailMapper.updateBatchById(collect2);
                }
                if (collect.size() > 0) {
                    purchaseReceiptDetailMapper.deleteBatchIds(collect);
                }
                //删除库存中的物料号码
                List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>()
                    .lambda().in(WmsStockInfo::getWsiMaterialNumber, collect1));
                wmsStockInfoMapper.deleteBatchIds(wmsStockInfoList);
            }

            //3、待交接的单据关结后，单据状态变为"已关结"，单据明细的物料状态变为已入库
            if (purchaseReceipt.getStatus() == 3) {
                purchaseReceipt.setStatus(4)
                    .setCloseReason(purchaseReceiptVo.getCloseReason())
                    .setClosingBy(LoginHelper.getUsername())
                    .setClosingTime(new Date());

                List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(
                    new QueryWrapper<PurchaseReceiptDetail>()
                        .lambda().eq(PurchaseReceiptDetail::getReceiptId, purchaseReceipt.getId()));
                for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                    entity.setStatus(3);
                }
                purchaseReceiptDetailMapper.updateBatchById(purchaseReceiptDetailList);
            }
            //4、待入库的单据关节后，单据状态变为"已关结"
            if (purchaseReceipt.getStatus() == 1) {
                purchaseReceipt.setStatus(4)
                    .setCloseReason(purchaseReceiptVo.getCloseReason())
                    .setClosingBy(LoginHelper.getUsername())
                    .setClosingTime(new Date());
            }
        } else {
            throw new GlobalException("已完成、已关结不可重复关结");
        }
        return purchaseReceiptMapper.updateById(purchaseReceipt) > 0;


    }


    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public PurchaseReceiptDto getView(Long id) {
        PurchaseReceiptDto receiptViewById = purchaseReceiptMapper.getReceiptViewById(id);
        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();
        //单据类型
        receiptViewById.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(receiptViewById.getDocumentType())));

        List<PurchaseVo> purchaseVos = new ArrayList<>();
        PurchaseVo purchaseVo = new PurchaseVo();
        purchaseVo.setPurchaseOrderNo(receiptViewById.getPurchaseOrderNo());
        purchaseVo.setPlannedWeight(receiptViewById.getPlannedWeight());
        purchaseVo.setWarehousingWarehouse(receiptViewById.getWarehousingWarehouse());
        //物料单位
        purchaseVo.setMaterialUnit(receiptViewById.getMaterialUnit());
        purchaseVo.setUnitDict(unitByCodeToMap.get(receiptViewById.getMaterialUnit()).getUnitName());
        //获取仓库名称
        purchaseVo.setWarehousingWarehouseDict(receiptViewById.getWarehousingWarehouseDict());
        purchaseVo.setMaterialName(receiptViewById.getMaterialName());
        purchaseVo.setMaterialCode(receiptViewById.getMaterialCode());
        purchaseVo.setMaterialSpec(receiptViewById.getMaterialSpec());
        //辅助属性
        List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + receiptViewById.getTenantId(), String.valueOf(receiptViewById.getMaterialId()));
        purchaseVo.setAuxiliaryAttribute(statsArray);

        purchaseVos.add(purchaseVo);
        receiptViewById.setProcurementList(purchaseVos);
        return receiptViewById;
    }


    /**
     * 修改
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReceipt(PurchaseReceiptVo purchaseReceiptVo) {
        PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(purchaseReceiptVo.getId());
        if (purchaseReceipt.getGenerationMethod() == 1) {
            throw new GlobalException("自动生成的单据不可修改");
        }
        if (purchaseReceipt.getStatus() == 1) {
            purchaseReceipt.setReceiveType(purchaseReceiptVo.getReceiveType());
            purchaseReceipt.setSupplierCode(purchaseReceiptVo.getSupplierCode());
            purchaseReceipt.setEstimatedTime(purchaseReceiptVo.getEstimatedTime());
            purchaseReceipt.setRemark(purchaseReceiptVo.getRemark());
            List<PurchaseVo> procurementList = purchaseReceiptVo.getProcurementList();
            for (PurchaseVo entity : procurementList) {
                purchaseReceipt.setPurchaseOrderNo(entity.getPurchaseOrderNo())
                    .setMaterialUnit(entity.getMaterialUnit())
                    .setPlannedWeight(entity.getPlannedWeight())
                    .setWarehousingWarehouse(Long.parseLong(entity.getWarehousingWarehouse()))
                    .setMaterialCode(entity.getMaterialCode())
                    .setMaterialId(entity.getMaterialId());
            }
            return purchaseReceiptMapper.updateById(purchaseReceipt) > 0;
        } else {
            throw new GlobalException("只能修改待入库的数据");
        }

    }

    /**
     * 删除
     *
     * @param idStr
     * @return
     */
    @Override
    public boolean deleteReceipt(String idStr) {
        List<String> idList = Arrays.asList(idStr.split(","));
        if (idList.size() == 0) {
            throw new GlobalException("请至少选择一条数据");
        }
        List<PurchaseReceipt> purchaseReceiptList = new ArrayList<>();
        List<PurchaseReceipt> purchaseReceipts = purchaseReceiptMapper.selectList(new QueryWrapper<PurchaseReceipt>().lambda().in(PurchaseReceipt::getId, idList));
        for (PurchaseReceipt entity : purchaseReceipts) {
            if (entity.getStatus() == 1) {
                purchaseReceiptList.add(entity);
            } else {
                throw new GlobalException("只能删除待入库的单据");
            }
        }
        List<PurchaseReceipt> deleteList = new ArrayList<>();
        for (PurchaseReceipt entity : purchaseReceiptList) {
            if (entity.getGenerationMethod() == 2) {
                deleteList.add(entity);
            } else {
                throw new GlobalException("自动生成的单据不能删除");
            }
        }
        return purchaseReceiptMapper.deleteBatchIds(deleteList) > 0;
    }


//    /**
//     * 入库/送检
//     *
//     * @param warehousInspectionVo
//     * @return
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean warehousInspection(WarehousInspectionVo warehousInspectionVo) throws Exception {
//        PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(warehousInspectionVo.getId());
//        //获取供应商信息
//        R<OrderSupplierManagementDto> view = remoteSupplierService.view(purchaseReceipt.getSupplierId());
//        if (purchaseReceipt.getStatus() == 1 || purchaseReceipt.getStatus() == 2) {
//            //修改状态为入库中
//            purchaseReceipt.setStatus(2);
//
//            List<InspectionVo> warehousInspectionList = warehousInspectionVo.getInspectionList();
//
//            for (InspectionVo entity : warehousInspectionList) {
//                List<IncomingMaterialPrintingDetail> incomingMaterialPrintingDetails = new ArrayList<>();
//                IncomingMaterialPrinting incomingMaterialPrinting = new IncomingMaterialPrinting();
//                incomingMaterialPrinting.setDocumentType(purchaseReceipt.getDocumentType())
//                        .setDeptId(LoginHelper.getDeptId())
//                        .setReceiptNo(purchaseReceipt.getReceiptNo())
//                        .setSupplierId(purchaseReceipt.getSupplierId())
//                        .setQuantityBatch(entity.getNumberCars())
//                        .setCreateBy(LoginHelper.getUsername())
//                        .setCreateTime(new Date())
//                        //唯一标识
//                        .setOnlyMark(remoteCodeService.splitList("IMP"))
//                        //生成批次号
//                        .setBatchNo(batchNoGenerate())
//                        .setMaterialCode(purchaseReceipt.getMaterialCode());
//                //如果是免检就保存打印状态为待打印，如果不是就保存待检验
//                if (warehousInspectionVo.getInspectionExemption() == 1) {
//                    incomingMaterialPrinting.setPrintStatus(2);
//                } else {
//                    incomingMaterialPrinting.setPrintStatus(1);
//                }
//                incomingMaterialPrintingMapper.insert(incomingMaterialPrinting);
//                //存储打印明细数据
//                for (int i = 0; i <= entity.getNumberCars() - 1; i++) {
//                    IncomingMaterialPrintingDetail incomingMaterialPrintingDetail = new IncomingMaterialPrintingDetail();
//                    incomingMaterialPrintingDetail.setPrintId(incomingMaterialPrinting.getId())
//                            .setBatchNo(incomingMaterialPrinting.getBatchNo())
//                            .setReceiptQuantity(1)
//                            .setMaterialCategory(purchaseReceipt.getMaterialCategory())
//                            .setMaterialId(purchaseReceipt.getMaterialId())
//                            .setMaterialCode(incomingMaterialPrinting.getMaterialCode())
//                            .setMaterialNumber(feignService.splitList("CGRKDYNUM"))
//                            .setReceiptId(purchaseReceipt.getId());
//                    //如果是免检就保存净重和毛重数据
//                    if (warehousInspectionVo.getInspectionExemption() == 1) {
//                        incomingMaterialPrintingDetail.setGrossWeight(entity.getNetWeight() / entity.getNumberCars());
//                        incomingMaterialPrintingDetail.setNetWeight(entity.getNetWeight() / entity.getNumberCars());
//                    } else {
//                        incomingMaterialPrintingDetail.setGrossWeight(entity.getNetWeight() / entity.getNumberCars());
//                    }
//                    incomingMaterialPrintingDetails.add(incomingMaterialPrintingDetail);
//                }
//                incomingMaterialPrintingDetailService.saveBatch(incomingMaterialPrintingDetails);
//
//                // 生成品质检验单
//                if (incomingMaterialPrinting.getPrintStatus() == 1) {
//                    Long menuId = feignService.getIdByMenuName("采购入库");
//                    AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
//                    SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
//                    if (sysDocument.getDocCode() == null) {
//                        throw new GlobalException("未找到相应的检验项目，请前往“质量管理“---”检验配置”页配置");
//                    }
//                    List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
//                    if (documentCheckDtoList.size() < 1) {
//                        throw new GlobalException("未进行检验单生成配置");
//                    }
//                    //通过物料编码获取物料类别
//                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, purchaseReceipt.getMaterialCode()));
//
//
//                    for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
//                        if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
//                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
//                            qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
//                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
//                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
//                            qualityInspectionDocumentVo.setMaterialCode(purchaseReceipt.getMaterialCode());
//                            qualityInspectionDocumentVo.setBatchNo(incomingMaterialPrinting.getBatchNo());
//                            qualityInspectionDocumentVo.setAssociatedNo(incomingMaterialPrinting.getReceiptNo());
//                            qualityInspectionDocumentVo.setOnlyMark(incomingMaterialPrinting.getOnlyMark());
//                            qualityInspectionDocumentVo.setDifferentString(supplierManagement.getSupplierNum());
//                            qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
//                            qualityInspectionDocumentVo.setModeType(10);
//
//                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
//                            for (IncomingMaterialPrintingDetail detail : incomingMaterialPrintingDetails) {
//                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
//                                materialNumberAndBatchNoVo.setBatchNo(detail.getBatchNo());
//                                materialNumberAndBatchNoVo.setMaterialNumber(detail.getMaterialNumber());
//                                materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
//                            }
//                            qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);
//
//                            AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
//                            String code = add.get("code").toString();
//                            if ("500".equals(code)) {
//                                throw new GlobalException("生成品质检验单失败!");
//                            }
//                        } else {
//                            throw new GlobalException("所选物料和送检物料类型不一致，请核实相关配置");
//                        }
//                    }
//                }
//            }
//            return updateById(purchaseReceipt);
//        } else {
//            throw new GlobalException("只能操作待入库的数据");
//        }
//    }

    /**
     * 导出
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    public List<PurchaseReceiptExport> getInfoExport(PurchaseReceiptVo purchaseReceiptVo) {
        List<PurchaseReceiptExportDto> purchaseReceipts;

        if (purchaseReceiptVo.getIdStr() == null) {
            purchaseReceipts = purchaseReceiptMapper.getReceiptListOut(purchaseReceiptVo);
        } else {
            List<String> idList = Arrays.asList(purchaseReceiptVo.getIdStr().split(","));
            purchaseReceipts = purchaseReceiptMapper.getDataByIdStr(idList);
        }

        List<PurchaseReceiptExport> exportList = new ArrayList<>();
        for (PurchaseReceiptExportDto entity : purchaseReceipts) {
            PurchaseReceiptExport purchaseReceiptExport = new PurchaseReceiptExport();

//            BeanUtils.copyProperties(entity, purchaseReceiptExport);
            //供应商
            purchaseReceiptExport.setSupplierName(entity.getSupplierName());

            exportList.add(purchaseReceiptExport);
        }
        return exportList;
    }

    /**
     * 采购入库 pda入库
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto warehousingPda(PickingRestDbVo pickingRestDbVo) {
        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();
        PurchaseReceipt byId = purchaseReceiptMapper.selectById(pickingRestDbVo.getId());
        //获取物料信息
        PublicMaterial publicMaterial = publicMaterialMapper.selectOne(new QueryWrapper<PublicMaterial>()
            .lambda().eq(PublicMaterial::getMaterialCode, byId.getMaterialCode()));
        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("采购入库");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        if (sysDocument == null) {
            throw new GlobalException("未获取到单据配置信息");
        }
        if (byId.getStatus() == 1 || byId.getStatus() == 2) {
            //扫码入库
            if ("1".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("该仓库不存在，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setCode("200");
                    pickingRestDbDto.setMessage("操作成功");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据物料号码查询明细信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    PurchaseReceiptDetail purchaseReceiptDetail = purchaseReceiptDetailMapper.selectOne(new QueryWrapper<PurchaseReceiptDetail>().lambda()
                        .eq(PurchaseReceiptDetail::getMaterialNumber, pickingRestDbVo.getInputValue())
                        .eq(PurchaseReceiptDetail::getReceiptId, byId.getId()));
                    if (purchaseReceiptDetail == null) {
                        pickingRestDbDto.setMessage("不存在该明细，请核实!");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    if (purchaseReceiptDetail.getStatus() == 2) {
                        pickingRestDbDto.setMessage("该数据已经入库");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(pickingRestDbVo.getId());
                    //判断是否配置超收(如果未配置超收且实际量大于等于计划量就给提示)
//                    if (sysDocument.getDocExcessMark() == 2) {
//                        double aDouble;
//                        if (purchaseReceipt.getActualQuantity() == null) {
//                            aDouble = 0;
//                        } else {
//                            aDouble = Double.parseDouble(purchaseReceipt.getActualQuantity());
//                        }
//                        //每一次将实际量和计划量进行比较
//                        double plannedWeight = purchaseReceipt.getPlannedWeight();
//                        boolean b = (int) Math.round(aDouble) >= (int) Math.round(plannedWeight);
//                        if (b) {
//                            //修改单据为已完成
//                            purchaseReceipt.setStatus(3);
//                            purchaseReceiptMapper.updateById(purchaseReceipt);
//                            List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>()
//                                .lambda().eq(PurchaseReceiptDetail::getReceiptId, purchaseReceipt.getId()));
//                            //修改来料打印状态为已完成
//                            IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>()
//                                .lambda().eq(IncomingMaterialPrinting::getReceiptNo, purchaseReceipt.getReceiptNo())
//                                .eq(IncomingMaterialPrinting::getBatchNo, purchaseReceiptDetailList.get(0).getBatchNo()));
//                            //把对应的来料打印数据状态修改为已完成
//                            incomingMaterialPrinting.setPrintStatus(4);
//                            incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting);
//                            pickingRestDbDto.setMessage("该单据未配置超收，且实际量大于等于计划量，无法继续入库，请核实");
//                            pickingRestDbDto.setCode("500");
//                            return pickingRestDbDto;
//                        }
//                    }

                    //获取物料类别信息
                    SysApiCategoryDto data = remoteCodingService.getByCode(purchaseReceiptDetail.getMaterialCode()).getData();

                    if (purchaseReceipt.getActualQuantity() == null) {
                        purchaseReceipt.setActualQuantity(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                        String s = bigDecimal.add(bigDecimal1).toString();
                        purchaseReceipt.setActualQuantity(s);
                    }
                    if (purchaseReceipt.getWarehousingNum() == null) {
                        purchaseReceipt.setWarehousingNum(1);
                    } else {
                        purchaseReceipt.setWarehousingNum(purchaseReceipt.getWarehousingNum() + 1);
                    }

                    MaterialUnitDto data1 = remoteUnitService.getUnitDataByCode(publicMaterial.getMaterialUnit()).getData();
                    //设置入库仓
                    purchaseReceipt.setWarehousingWarehouse(pickingRestDbVo.getCkId());

                    pickingRestDbDto.setQuantityIdentification(purchaseReceipt.getPlannedWeight() + "/" + purchaseReceipt.getActualQuantity());
                    pickingRestDbDto.setMessage("物料号码:" + purchaseReceiptDetail.getMaterialNumber() + "数量:" + purchaseReceiptDetail.getNetWeight() + "," + "录入成功");
                    pickingRestDbDto.setUnit(String.valueOf(publicMaterial.getMaterialUnit()));
                    pickingRestDbDto.setUnitDict(data1.getUnitName());

                    //修改仓库表中对应的数据状态
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, purchaseReceiptDetail.getMaterialNumber()));
                    wmsStockInfo.setWsiMaterialStatus(2);
                    wmsStockInfo.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                    wmsStockInfo.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                    wmsStockInfo.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                    wmsStockInfo.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                    wmsStockInfo.setWsiDocNum(byId.getReceiptNo());
                    wmsStockInfo.setWsiCategory(String.valueOf(data.getCategoryId()));
                    wmsStockInfo.setWsiMaterialType(Long.parseLong(data.getCategoryType()));
                    wmsStockInfo.setWsiReveiveTime(new Date());
                    wmsStockInfo.setWsiConnectNum(byId.getPurchaseOrderNo());
                    wmsStockInfo.setWsiMaterialGrade("1");
                    wmsStockInfo.setUnitPrice(byId.getUnitPrice());
                    if (data1.getUnitQuantity() != null) {
                        wmsStockInfo.setWsiMinunitNum(Integer.parseInt(data1.getUnitQuantity()));
                    }
                    wmsStockInfoMapper.updateById(wmsStockInfo);
                    //修改明细状态
                    purchaseReceiptDetail.setStatus(2);
//                    if (sysDocument.getDocHandoverMark() == 1) {
//                        purchaseReceiptDetail.setStatus(2);
//                    } else {
//                        purchaseReceiptDetail.setStatus(3);
//                    }
                    purchaseReceiptDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                    purchaseReceiptDetail.setWarehouseInTime(new Date());
                    purchaseReceiptDetail.setWarehouseInBy(LoginHelper.getUsername());
                    purchaseReceiptDetailMapper.updateById(purchaseReceiptDetail);
                    //校验该采购入库的全部明细状态是否都为已入库，如果不全是就修改为入库中，否则就修改为已完成
                    List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, pickingRestDbVo.getId()));
                    boolean isTrue = true;
                    for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                        if (entity.getStatus() == 1) {
                            isTrue = false;
                            break;
                        }
                    }

                    //实际量
                    double aDouble = Double.parseDouble(purchaseReceipt.getActualQuantity());
                    //每一次将实际量和计划量进行比较
                    double plannedWeight = purchaseReceipt.getPlannedWeight();
                    boolean b = (int) Math.round(aDouble) >= (int) Math.round(plannedWeight);

                    //如果实际量大于等于计划量并且采购入库的全部明细状态为已入库
                    if (isTrue && b) {
                        purchaseReceipt.setStatus(3);
                    } else {
                        purchaseReceipt.setStatus(2);

                    }


//                    // 将数据回传至采购订单
//                    UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
//                    updatePurchaseOrderDataVo.setActualQuantity(String.valueOf(purchaseReceiptDetail.getNetWeight()));
//                    updatePurchaseOrderDataVo.setPurchaseOrderNo(purchaseReceipt.getPurchaseOrderNo());
//                    remotePurchaseOrderService.updateOrderData(updatePurchaseOrderDataVo);

                    //修改打印数据状态
                    List<PurchaseReceiptDetail> purchaseReceiptDetailList1 = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, purchaseReceipt.getId()));

                    Map<String, List<PurchaseReceiptDetail>> collect = purchaseReceiptDetailList1.stream().collect(Collectors.groupingBy(PurchaseReceiptDetail::getBatchNo));
                    for (Map.Entry<String, List<PurchaseReceiptDetail>> materialGroupEntity : collect.entrySet()) {
                        boolean isAll = true;
                        for (PurchaseReceiptDetail entity1 : materialGroupEntity.getValue()) {
                            if (entity1.getStatus() != 2) {
                                isAll = false;
                                break;
                            }
                        }
                        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getReceiptNo, purchaseReceipt.getReceiptNo()).eq(IncomingMaterialPrinting::getBatchNo, materialGroupEntity.getKey()));
                        if (isAll) {
                            //把对应的来料打印数据状态修改为已完成
                            incomingMaterialPrinting.setPrintStatus(4);
                        } else {
                            //把对应的来料打印数据状态修改为待入库
                            incomingMaterialPrinting.setPrintStatus(3);
                        }
                        incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting);
                    }
                    //判断该单据在打印页面是否还存在未入库数据
                    String receiptNo = purchaseReceipt.getReceiptNo();
                    List<IncomingMaterialPrinting> incomingMaterialPrintings = incomingMaterialPrintingMapper.selectList(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getReceiptNo, receiptNo));
                    boolean printAll = true;
                    for (IncomingMaterialPrinting entity : incomingMaterialPrintings) {
                        if (entity.getPrintStatus() != 4) {
                            printAll = false;
                            break;
                        }
                    }
                    if (printAll) {
                        purchaseReceipt.setStatus(3);
                    } else {
                        purchaseReceipt.setStatus(2);
                    }
                    purchaseReceiptMapper.updateById(purchaseReceipt);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
            }
            //批次入库
            if ("2".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("该仓库不存在，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setMessage("操作成功");
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据批次号查询明细信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda()
                        .eq(PurchaseReceiptDetail::getBatchNo, pickingRestDbVo.getInputValue())
                        .eq(PurchaseReceiptDetail::getReceiptId, byId.getId())
                        .eq(PurchaseReceiptDetail::getStatus, 1));
                    if (purchaseReceiptDetailList.size() < 1) {
                        pickingRestDbDto.setMessage("该批次号下无待入库数据，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    //净重总数
                    BigDecimal bigDecimalNetWeight = new BigDecimal(0);
                    //入库数量总数
                    BigDecimal bigDecimalWarehouseNum = new BigDecimal(0);
                    //循环明细信息
                    for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                        bigDecimalNetWeight = bigDecimalNetWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                        bigDecimalWarehouseNum = bigDecimalWarehouseNum.add(new BigDecimal(String.valueOf(entity.getReceiptQuantity())));
                    }
                    //获取物料类别信息
                    SysApiCategoryDto data = remoteCodingService.getByCode(purchaseReceiptDetailList.get(0).getMaterialCode()).getData();
                    //获取采购入库信息
                    PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(pickingRestDbVo.getId());
                    MaterialUnitDto data1 = remoteUnitService.getUnitDataByCode(publicMaterial.getMaterialUnit()).getData();


                    //如果单位是千克
                    if (purchaseReceipt.getActualQuantity() == null) {
                        purchaseReceipt.setActualQuantity(bigDecimalNetWeight.toString());
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                        String s = bigDecimal.add(bigDecimalNetWeight).toString();
                        purchaseReceipt.setActualQuantity(s);
                    }
                    //设置入库仓
                    purchaseReceipt.setWarehousingWarehouse(pickingRestDbVo.getCkId());

                    //采购入库数量
                    if (purchaseReceipt.getWarehousingNum() == null) {
                        purchaseReceipt.setWarehousingNum(purchaseReceiptDetailList.size());
                    } else {
                        purchaseReceipt.setWarehousingNum(purchaseReceipt.getWarehousingNum() + purchaseReceiptDetailList.size());
                    }
                    //设置返回值
                    pickingRestDbDto.setQuantityIdentification(purchaseReceipt.getPlannedWeight() + "/" + purchaseReceipt.getActualQuantity());
                    pickingRestDbDto.setMessage("批次号:" + purchaseReceiptDetailList.get(0).getBatchNo() + "," + "数量:" + bigDecimalNetWeight + "," + "录入成功");
//                    pickingRestDbDto.setUnit(purchaseReceipt.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(data1.getUnitName());
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(bigDecimalWarehouseNum));


                    //修改仓库表中对应的数据状态
                    List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, pickingRestDbVo.getInputValue()));
                    List<WmsStockInfo> wmsStockInfoArrayList = new ArrayList<>();
                    for (WmsStockInfo entity : wmsStockInfoList) {
                        entity.setWsiMaterialStatus(2);
                        entity.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                        entity.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                        entity.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                        entity.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                        entity.setWsiDocNum(byId.getReceiptNo());
                        entity.setWsiConnectNum(byId.getPurchaseOrderNo());
                        entity.setWsiCategory(String.valueOf(data.getCategoryId()));
                        entity.setWsiMaterialType(Long.parseLong(data.getCategoryType()));
                        entity.setWsiReveiveTime(new Date());
                        entity.setWsiMaterialGrade("1");
                        entity.setUnitPrice(byId.getUnitPrice());
                        if (data1.getUnitQuantity() != null) {
                            entity.setWsiMinunitNum(Integer.parseInt(data1.getUnitQuantity()));
                        }
                        wmsStockInfoArrayList.add(entity);
                    }
                    wmsStockInfoMapper.updateBatchById(wmsStockInfoArrayList);
                    //修改明细状态
                    List<PurchaseReceiptDetail> detailList = new ArrayList<>();
                    for (PurchaseReceiptDetail receiptDetail : purchaseReceiptDetailList) {
                        receiptDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                        receiptDetail.setWarehouseInTime(new Date());
                        receiptDetail.setWarehouseInBy(LoginHelper.getUsername());
//                        if (sysDocument.getDocExcessMark() == 1) {
//                            receiptDetail.setStatus(2);
//                        } else {
//                            receiptDetail.setStatus(3);
//                        }
                        receiptDetail.setStatus(2);
                        detailList.add(receiptDetail);
                    }
                    purchaseReceiptDetailMapper.updateBatchById(detailList);
                    //校验该采购入库的全部明细状态是否都为已入库，如果不全是就修改为入库中，否则就修改为已完成
                    List<PurchaseReceiptDetail> receiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, pickingRestDbVo.getId()));
                    boolean isTrue = true;
                    for (PurchaseReceiptDetail entity : receiptDetailList) {
                        if (entity.getStatus() != 2) {
                            isTrue = false;
                            break;
                        }
                    }

                    //实际量
                    double aDouble = Double.parseDouble(purchaseReceipt.getActualQuantity());
                    //每一次将实际量和计划量进行比较
                    double plannedWeight = purchaseReceipt.getPlannedWeight();
                    boolean b = (int) Math.round(aDouble) >= (int) Math.round(plannedWeight);

                    if (isTrue && b) {
                        if (sysDocument.getDocExcessMark() == 1) {
                            purchaseReceipt.setStatus(2);
                        } else {
                            purchaseReceipt.setStatus(3);
                        }
                    } else {
//                        if (sysDocument.getDocExcessMark() == 1) {
//                            purchaseReceipt.setStatus(3);
//                        } else {
//                            purchaseReceipt.setStatus(2);
//                        }
                        purchaseReceipt.setStatus(2);
                    }

                    //修改采购入库状态
                    purchaseReceiptMapper.updateById(purchaseReceipt);
                    pickingRestDbDto.setCode("200");
//                    // 将数据回传至采购订单
//                    UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
//                    updatePurchaseOrderDataVo.setActualQuantity(String.valueOf(bigDecimalNetWeight));
//                    updatePurchaseOrderDataVo.setPurchaseOrderNo(purchaseReceipt.getPurchaseOrderNo());
//                    remotePurchaseOrderService.updateOrderData(updatePurchaseOrderDataVo);

                    //修改采购打印状态
                    IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getBatchNo, pickingRestDbVo.getInputValue()));
                    incomingMaterialPrinting.setPrintStatus(4);
                    incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting);
                    //判断该单据在打印页面是否还存在未入库数据
                    String receiptNo = purchaseReceipt.getReceiptNo();
                    List<IncomingMaterialPrinting> incomingMaterialPrintings = incomingMaterialPrintingMapper.selectList(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getReceiptNo, receiptNo));
                    boolean printAll = true;
                    for (IncomingMaterialPrinting entity : incomingMaterialPrintings) {
                        if (entity.getPrintStatus() != 4) {
                            printAll = false;
                            break;
                        }
                    }
                    if (printAll) {
                        if (sysDocument.getDocExcessMark() == 1) {
                            purchaseReceipt.setStatus(2);
                        } else {
                            purchaseReceipt.setStatus(3);
                        }
                    } else {
//                        if (sysDocument.getDocExcessMark() == 1) {
//                            purchaseReceipt.setStatus(3);
//                        } else {
//                            purchaseReceipt.setStatus(2);
//                        }
                        purchaseReceipt.setStatus(2);

                    }
                    purchaseReceiptMapper.updateById(purchaseReceipt);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
            }
            //库位撤销
            if ("3".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("该仓库不存在，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setMessage("操作成功");
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据物料号码查询信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()).eq(WmsStockInfo::getWsiMaterialStatus, 2));
                    if (wmsStockInfo == null) {
                        pickingRestDbDto.setMessage("撤销失败，请核实后再录入");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    wmsStockInfo.setWsiMaterialStatus(1);
                    wmsStockInfo.setWsiWarehourse("");
                    wmsStockInfo.setWsiReservoirArea("");
                    wmsStockInfo.setWsiStorageLoaction("");
                    wmsStockInfo.setWsiWarehourseInfo("");
                    wmsStockInfoMapper.updateById(wmsStockInfo);

                    //获取采购入库信息
                    PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(pickingRestDbVo.getId());
                    String unitName = remoteUnitService.getUnitDataByCode(publicMaterial.getMaterialUnit()).getData().getUnitName();

                    //同时修改采购入库明细状态
                    PurchaseReceiptDetail purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectOne(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                    purchaseReceiptDetailList.setStatus(1);
                    purchaseReceiptDetailList.setWarehouseMessage("");
                    purchaseReceiptDetailList.setWarehouseInTime(null);
                    purchaseReceiptDetailList.setWarehouseInBy("");
                    purchaseReceiptDetailMapper.updateById(purchaseReceiptDetailList);

                    //扣减实际量
                    BigDecimal subtract = new BigDecimal(purchaseReceipt.getActualQuantity()).subtract(new BigDecimal(String.valueOf(purchaseReceiptDetailList.getNetWeight())));
                    purchaseReceipt.setActualQuantity(subtract.toString());
                    //减少入库数量
                    if (purchaseReceipt.getWarehousingNum() != 0) {
                        purchaseReceipt.setWarehousingNum(purchaseReceipt.getWarehousingNum() - 1);
                    }
                    //修改采购入库单状态为入库中
                    purchaseReceipt.setStatus(2);
                    purchaseReceiptMapper.updateById(purchaseReceipt);
                    // 将数据回传至采购订单
//                    UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
//                    updatePurchaseOrderDataVo.setActualQuantity(String.valueOf(purchaseReceiptDetailList.getNetWeight()));
//                    updatePurchaseOrderDataVo.setPurchaseOrderNo(purchaseReceipt.getPurchaseOrderNo());
//                    remotePurchaseOrderService.updateOrderDataSub(updatePurchaseOrderDataVo);

                    //设置返回信息
                    pickingRestDbDto.setMessage("物料号码:" + purchaseReceiptDetailList.getMaterialNumber() + "," + "数量:" + "1" + "," + "撤销成功");
                    pickingRestDbDto.setQuantityIdentification(purchaseReceipt.getPlannedWeight() + "/" + purchaseReceipt.getActualQuantity());
                    pickingRestDbDto.setUnitDict(unitName);
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(purchaseReceipt.getWarehousingNum()));
                    pickingRestDbDto.setCode("200");
                    pickingRestDbDto.setMessage("操作成功");
                    return pickingRestDbDto;
                }
            }
        } else {
            pickingRestDbDto.setMessage("只能操作待入库和入库中得数据");
            pickingRestDbDto.setCode("500");
            return pickingRestDbDto;
        }
        pickingRestDbDto.setCode("500");
        pickingRestDbDto.setMessage("步骤错误");
        return pickingRestDbDto;
    }

    /**
     * 入库打印
     *
     * @param storagePrintingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean storagePrinting(StoragePrintingVo storagePrintingVo) throws Exception {
        //获取采购入库信息
        PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(storagePrintingVo.getId());
        //获取本次到货数
        Integer arrivalNumber = storagePrintingVo.getArrivalNumber();
        //获取明细数
        Integer detailNumber = storagePrintingVo.getDetailNumber();

        Integer printNum;
        BigDecimal divide;
        //打印方式
        Integer printType = storagePrintingVo.getPrintType();
        if (printType == 1) {
            //个数打印
            printNum = arrivalNumber;
            //每个明细数据的入库数量
            divide = new BigDecimal(String.valueOf(1));
        } else {
            //重量打印，打印次数= 入库数量/明细数量
            if (arrivalNumber % detailNumber != 0) {
                throw new GlobalException("明细数量需要能够被整除，请核实");
            } else {
                printNum = arrivalNumber / detailNumber;
                //每个明细数据的入库数量
                divide = new BigDecimal(printNum.toString());
            }
        }

        //判断每次打印时，是否超出了订单的总数量
        double plannedWeight = purchaseReceipt.getPlannedWeight();
        //实际量
        String actualQuantity = purchaseReceipt.getActualQuantity();
        BigDecimal add;
        if (actualQuantity == null) {
            add = new BigDecimal(String.valueOf(arrivalNumber));
        } else {
            //本次需打印的重量
            add = new BigDecimal(String.valueOf(arrivalNumber)).add(new BigDecimal(actualQuantity));
        }
        double v = Double.parseDouble(add.toString());
        if (v > plannedWeight) {
//            BigDecimal subtract = new BigDecimal(String.valueOf(plannedWeight)).subtract(new BigDecimal(String.valueOf(v)));
            throw new GlobalException("打印重量不能超出单据数量，建议本次重量不超过:" + plannedWeight);
        }


        //根据明细数生成来料打印数据
        IncomingMaterialPrinting incomingMaterialPrinting = new IncomingMaterialPrinting();
        incomingMaterialPrinting.setReceiptNo(purchaseReceipt.getReceiptNo())
            .setBatchNo(batchNoGenerate())
            .setPrintStatus(1)
            .setMaterialCode(purchaseReceipt.getMaterialCode())
            .setDocumentType(purchaseReceipt.getDocumentType())
            .setSupplierCode(purchaseReceipt.getSupplierCode())
            .setCreateBy(LoginHelper.getUsername())
            .setCreateTime(new Date());
        if (printType == 1) {
            incomingMaterialPrinting.setQuantityBatch(Long.parseLong(arrivalNumber.toString()));
        } else {
            incomingMaterialPrinting.setQuantityBatch(Long.parseLong(detailNumber.toString()));
        }

        boolean b = incomingMaterialPrintingMapper.insert(incomingMaterialPrinting) > 0;
        //生成条数
        Integer total;
        if (printType == 1) {
            total = arrivalNumber;
        } else {
            total = detailNumber;
        }
        if (b) {
            //生成明细数据
            List<IncomingMaterialPrintingDetail> detailList = new ArrayList<>();
            for (int i = 0; i < total; i++) {
                IncomingMaterialPrintingDetail detail = new IncomingMaterialPrintingDetail();
                detail.setMaterialCode(purchaseReceipt.getMaterialCode())
                    .setReceiptId(purchaseReceipt.getId())
                    .setMaterialNumber(remoteCodeService.splitList("CGRKDYNUM"))
                    .setMaterialUnit(purchaseReceipt.getMaterialUnit())
                    .setBatchNo(incomingMaterialPrinting.getBatchNo())
                    .setPrintId(incomingMaterialPrinting.getId())
                    .setNetWeight(Double.parseDouble(divide.toString()));
                detailList.add(detail);
            }
            incomingMaterialPrintingDetailMapper.insertBatch(detailList);
        }
        return b;
    }

    /**
     * 根据采购订单状态修改采购入库状态(feign调用)
     *
     * @param updateReceiptStatusVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReceiptStatus(UpdateReceiptStatusVo updateReceiptStatusVo) {

        List<PurchaseReceipt> purchaseReceipt = purchaseReceiptMapper.selectList(new QueryWrapper<PurchaseReceipt>().lambda().eq(PurchaseReceipt::getPurchaseOrderNo, updateReceiptStatusVo.getPurchaseOrderNo()));
        if (purchaseReceipt.size() > 0) {
            for (PurchaseReceipt entity : purchaseReceipt) {
                //已完成、已关结不可重复关结；
                if (entity.getStatus() != 3 || entity.getStatus() != 4) {
                    entity.setStatus(updateReceiptStatusVo.getUpdateValue());
                    // 入库中的单据关结后，单据状态更新为“已关结”，已扫描过的条码为在库（采购入库未扫描到的条码从库存中删除）
                    List<PurchaseReceiptDetail> purchaseReceiptDetails = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, entity.getId()));
                    if (purchaseReceiptDetails.size() > 0) {
                        //获取未扫描的明细数据
                        List<String> materialNumberList = purchaseReceiptDetails.stream()
                            .filter(t -> t.getStatus() == 1)
                            .map(PurchaseReceiptDetail::getMaterialNumber)
                            .collect(Collectors.toList());
                        //将对应号码的数据在仓库中进行删除
                        if (materialNumberList.size() > 0) {
                            List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                            wmsStockInfoMapper.deleteBatchIds(wmsStockInfos);
                        }
                    }
                }
            }
            return purchaseReceiptMapper.updateBatchById(purchaseReceipt);
        } else {
            throw new GlobalException("没有查询到相关采购入库单,请核实!");
        }
    }

    /**
     * 采购入库交接
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    public PickingRestHandoverDto handover(PickingRestDbVo pickingRestDbVo) {
        PickingRestHandoverDto pickingRestHandoverDto = new PickingRestHandoverDto();
        PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(pickingRestDbVo.getId());

        if (purchaseReceipt.getStatus() != 3) {
            pickingRestHandoverDto.setResultCode("500");
            pickingRestHandoverDto.setMessage("只能操作待交接的单据");
            return pickingRestHandoverDto;
        }
        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("采购入库");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        if (sysDocument == null) {
            throw new GlobalException("未获取到单据配置信息");
        }
        //第一步根据工号查询交接人
        //如果是整单
        if ("3".equals(sysDocument.getDocHandoverMethod())) {
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                R<SysUser> byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = byUserName.getData();

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(Integer.parseInt(sysDocument.getDocHandoverMethod()));
                pickingRestHandoverDto.setResultCode("200");

                BigDecimal bigDecimalNetWeight = new BigDecimal(0);
                //根据id获取明细信息
                List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, pickingRestDbVo.getId()));
                for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                    entity.setStatus(3);
                    bigDecimalNetWeight = bigDecimalNetWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                }
                purchaseReceiptDetailMapper.updateBatchById(purchaseReceiptDetailList);
                //修改采购入库状态为已经完成
                purchaseReceipt.setStatus(5);
                //修改交接量
                if (purchaseReceipt.getHandoverWeight() != null) {
                    BigDecimal add = new BigDecimal(purchaseReceipt.getHandoverWeight()).add(bigDecimalNetWeight);
                    purchaseReceipt.setHandoverWeight(add.toString());
                } else {
                    purchaseReceipt.setHandoverWeight(bigDecimalNetWeight.toString());
                }
                //修改交接数
                if (purchaseReceipt.getHandoverNum() != null) {
                    BigDecimal add = new BigDecimal(purchaseReceipt.getHandoverNum()).add(new BigDecimal(String.valueOf(purchaseReceiptDetailList.size())));
                    purchaseReceipt.setHandoverNum(Integer.parseInt(add.toString()));
                } else {
                    purchaseReceipt.setHandoverNum(purchaseReceiptDetailList.size());
                }
                purchaseReceiptMapper.updateById(purchaseReceipt);

                //单位
                String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(purchaseReceipt.getMaterialUnit())).getData().getUnitName();

                //设置出参数据
                pickingRestHandoverDto.setQuantityIdentification(purchaseReceipt.getWarehousingWeight() + "/" + bigDecimalNetWeight + unitName);
                pickingRestHandoverDto.setOutHandoverActual(purchaseReceiptDetailList.size() + "/" + purchaseReceiptDetailList.size());
                pickingRestHandoverDto.setMessage("单据号:" + purchaseReceipt.getReceiptNo() + "," + "数量:" + purchaseReceiptDetailList.size() + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
//            }
        }

        //如果是批次
        if ("2".equals(sysDocument.getDocHandoverMethod())) {
            //第一步根据工号查询交接人
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                R<SysUser> byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = byUserName.getData();

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(Integer.parseInt(sysDocument.getDocHandoverMethod()));
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }

            if (pickingRestDbVo.getExecutionOrder() == 2) {
                //通过批次号查询明细数据
                List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getBatchNo, pickingRestDbVo.getInputValue()));
                if (purchaseReceiptDetailList.size() > 0) {

                    //单位
                    String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(purchaseReceipt.getMaterialUnit())).getData().getUnitName();

                    BigDecimal bigDecimalHand = new BigDecimal(0);
                    for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                        entity.setStatus(3);
                        bigDecimalHand = bigDecimalHand.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                    }
                    purchaseReceiptDetailMapper.updateBatchById(purchaseReceiptDetailList);
                    //修改仓库表数据
                    List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, pickingRestDbVo.getInputValue()));
                    for (WmsStockInfo info : wmsStockInfoList) {
                        info.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoMapper.updateBatchById(wmsStockInfoList);
                    //交接重量
                    BigDecimal handoverWeight = bigDecimalHand.add(new BigDecimal(String.valueOf(purchaseReceipt.getActualQuantity())));

                    //入库数量
                    List<PurchaseReceiptDetail> detailListById = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, pickingRestDbVo.getId()));
                    //修改交接量
                    if (purchaseReceipt.getHandoverWeight() != null) {
                        BigDecimal add = new BigDecimal(purchaseReceipt.getHandoverWeight()).add(handoverWeight);
                        purchaseReceipt.setHandoverWeight(add.toString());
                    } else {
                        purchaseReceipt.setHandoverWeight(handoverWeight.toString());
                    }
                    //修改交接数
                    if (purchaseReceipt.getHandoverNum() != null) {
                        BigDecimal add = new BigDecimal(purchaseReceipt.getHandoverNum()).add(new BigDecimal(String.valueOf(detailListById.size())));
                        purchaseReceipt.setHandoverNum(Integer.parseInt(add.toString()));
                    } else {
                        purchaseReceipt.setHandoverNum(detailListById.size());
                    }
                    boolean isTrue = true;
                    for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                        if (entity.getStatus() != 3) {
                            isTrue = false;
                            break;
                        }
                    }
                    //如果明细都是已完成，就修改其他入库为已完成
                    if (isTrue) {
                        purchaseReceipt.setStatus(5);
                    }
                    purchaseReceiptMapper.updateById(purchaseReceipt);

                    //设置出参内容
                    pickingRestHandoverDto.setQuantityIdentification(purchaseReceipt.getWarehousingWeight() + "/" + handoverWeight + unitName);
                    pickingRestHandoverDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + "," + "数量:" + purchaseReceiptDetailList.size() + "," + "交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                    return pickingRestHandoverDto;

                } else {
                    pickingRestHandoverDto.setMessage("没有该批次号的数据，请核实后再操作");
                    pickingRestHandoverDto.setResultCode("500");
                    return pickingRestHandoverDto;
                }
            }
        }

        //单个物料
        if ("1".equals(sysDocument.getDocHandoverMethod())) {
            //第一步根据工号查询交接人
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                R<SysUser> byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = byUserName.getData();

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(Integer.parseInt(sysDocument.getDocHandoverMethod()));
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
            if (pickingRestDbVo.getExecutionOrder() == 2) {
//                //交接数量
//                BigDecimal handoverNum = new BigDecimal(1).add(new BigDecimal(pickingRestDbVo.getHandoverNum()));

                //根据物料条码获取明细信息
                PurchaseReceiptDetail purchaseReceiptDetail = purchaseReceiptDetailMapper.selectOne(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                //修改交接量
                if (purchaseReceipt.getHandoverWeight() != null) {
                    BigDecimal add = new BigDecimal(purchaseReceipt.getHandoverWeight()).add(new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight())));
                    purchaseReceipt.setHandoverWeight(add.toString());
                } else {
                    purchaseReceipt.setHandoverWeight(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                }
                //修改交接数
                if (purchaseReceipt.getHandoverNum() != null) {
                    purchaseReceipt.setHandoverNum(purchaseReceipt.getHandoverNum() + 1);
                } else {
                    purchaseReceipt.setHandoverNum(1);
                }
                //单位
                String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(purchaseReceipt.getMaterialUnit())).getData().getUnitName();
                //修改该明细状态为已经完成
                purchaseReceiptDetail.setStatus(3);
                purchaseReceiptDetailMapper.updateById(purchaseReceiptDetail);
                //修改仓库表数据
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, purchaseReceiptDetail.getMaterialNumber()));
                wmsStockInfo.setWsiMaterialStatus(2);
                wmsStockInfoMapper.updateById(wmsStockInfo);

                //判断明细是否都已经交接成功
                List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, pickingRestDbVo.getId()));
                boolean isTrue = true;
                for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                    if (entity.getStatus() != 3) {
                        isTrue = false;
                        break;
                    }
                }
                //如果明细都是已完成，就修改采购入库为已完成
                if (isTrue) {
                    purchaseReceipt.setStatus(5);
                }
                purchaseReceiptMapper.updateById(purchaseReceipt);

                //设置出参内容
                pickingRestHandoverDto.setQuantityIdentification(purchaseReceipt.getWarehousingWeight() + "/" + purchaseReceiptDetail.getNetWeight() + unitName);
                pickingRestHandoverDto.setOutHandoverActual(purchaseReceiptDetailList.size() + "/" + purchaseReceipt.getHandoverNum());
                pickingRestHandoverDto.setMessage("物料号码:" + purchaseReceiptDetail.getMaterialNumber() + "," + "数量:" + 1 + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
        }
        return pickingRestHandoverDto;
    }


    /**
     * 采购入库拣货完成
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCompleted(PickingRestDbVo pickingRestDbVo) {
        PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(pickingRestDbVo.getId());
        if (purchaseReceipt.getStatus() == 5) {
            throw new GlobalException("不能对已完成的单据进行拣货完成");
        }

        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("采购入库");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        if (sysDocument == null) {
            throw new GlobalException("未获取到单据配置信息");
        }
        //是否配置交接
        if (sysDocument.getDocHandoverMark() == 1) {
            purchaseReceipt.setStatus(3);
        } else {
            purchaseReceipt.setStatus(5);
        }
        return purchaseReceiptMapper.updateById(purchaseReceipt) > 0;
    }

    /**
     * 安卓pda 列表
     *
     * @param number
     * @return
     */
    @Override
    public TableDataInfo<AndroidPdaDto> androidPdaList(int number, PageQuery pageQuery) {
        Long deptId = LoginHelper.getDeptId();
        //采购入库列表
        if (number == 1) {
            Page<AndroidPdaDto> receiptAndroidList = purchaseReceiptMapper.getReceiptAndroidList(deptId, pageQuery.build());
            return TableDataInfo.build(receiptAndroidList);
        } else if (number == 2) {
            //完工入库
            Page<AndroidPdaDto> wipCompletionAndroidManualList = wipCompletionMapper.getWipCompletionAndroidManualList(deptId, pageQuery.build());
            return TableDataInfo.build(wipCompletionAndroidManualList);
        } else if (number == 3) {
            //生产退料
            Page<AndroidPdaDto> productionAndroidList = productionMaterialReturnMapper.getProductionAndroidList(deptId, pageQuery.build());
            return TableDataInfo.build(productionAndroidList);
        } else if (number == 4) {
            //销售退货
            Page<AndroidPdaDto> saleAndroidList = salesReturnMapper.getSaleAndroidList(deptId, pageQuery.build());
            return TableDataInfo.build(saleAndroidList);
        } else if (number == 5) {
            //委外入库
            Page<AndroidPdaDto> subcontractAndroidList = subcontractReceiptMapper.getSubcontractAndroidList(deptId, pageQuery.build());
            return TableDataInfo.build(subcontractAndroidList);
        } else if (number == 6) {
            //其他入库
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getMiscellaneousAndroidList(deptId, pageQuery.build());
            return TableDataInfo.build(miscellaneousAndroidList);
        } else if (number == 7) {
            //领料出库
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getStockList(deptId, pageQuery.build());
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "stock_out_info_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto androidPdaDto : miscellaneousAndroidList.getRecords()) {
                androidPdaDto.setStatusDict(statusMap.get(String.valueOf(androidPdaDto.getStatus())));
            }
            return TableDataInfo.build(miscellaneousAndroidList);
        } else if (number == 8) {
            //委外发货
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getOutsource(deptId, pageQuery.build());
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_outsource_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto androidPdaDto : miscellaneousAndroidList.getRecords()) {
                androidPdaDto.setStatusDict(statusMap.get(String.valueOf(androidPdaDto.getStatus())));
            }
            return TableDataInfo.build(miscellaneousAndroidList);
        } else if (number == 9) {
            //销售发货
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getSale(deptId, pageQuery.build());
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_sale_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto androidPdaDto : miscellaneousAndroidList.getRecords()) {
                androidPdaDto.setStatusDict(statusMap.get(String.valueOf(androidPdaDto.getStatus())));
            }
            return TableDataInfo.build(miscellaneousAndroidList);
        } else if (number == 10) {
            //返工出库
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getComplete(deptId, pageQuery.build());
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_complete_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto androidPdaDto : miscellaneousAndroidList.getRecords()) {
                androidPdaDto.setStatusDict(statusMap.get(String.valueOf(androidPdaDto.getStatus())));
            }
            return TableDataInfo.build(miscellaneousAndroidList);
        } else if (number == 11) {
            //采购退货
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getPurchase(deptId, pageQuery.build());
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_purchase_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto androidPdaDto : miscellaneousAndroidList.getRecords()) {
                androidPdaDto.setStatusDict(statusMap.get(String.valueOf(androidPdaDto.getStatus())));
            }
            return TableDataInfo.build(miscellaneousAndroidList);
        } else if (number == 12) {
            //委外退货
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getReturn(deptId, pageQuery.build());
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_returns_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto androidPdaDto : miscellaneousAndroidList.getRecords()) {
                androidPdaDto.setStatusDict(statusMap.get(String.valueOf(androidPdaDto.getStatus())));
            }
            return TableDataInfo.build(miscellaneousAndroidList);
        } else if (number == 13) {
            //委外退货
            Page<AndroidPdaDto> miscellaneousAndroidList = miscellaneousReceiptMapper.getRest(deptId, pageQuery.build());
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_rest_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto androidPdaDto : miscellaneousAndroidList.getRecords()) {
                androidPdaDto.setStatusDict(statusMap.get(String.valueOf(androidPdaDto.getStatus())));
            }
            return TableDataInfo.build(miscellaneousAndroidList);
        } else {
            return TableDataInfo.build();
        }
//        //采购入库列表
//        if (number == 1) {
//            //获取单据状态字典数据
//            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "purchase_receipt_status");
//            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//
//            Page<AndroidPdaDto> receiptAndroidList = purchaseReceiptMapper.getReceiptAndroidList(pageQuery.build());
//            List<AndroidPdaDto> records = receiptAndroidList.getRecords();
//            for (AndroidPdaDto entity : records) {
//                String unitName = remoteUnitService.getUnitDataByCode(entity.getMaterialUnit()).getData().getUnitName();
//                entity.setMaterialUnitDict(unitName);
//                entity.setStatusDict(statusMap.get(String.valueOf(entity.getStatus())));
//            }
//            return TableDataInfo.build(receiptAndroidList);
//        } else if (number == 4) {
//            //获取单据状态字典数据
//            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_return_status");
//            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//            //销售退货
//            Page<AndroidPdaDto> saleAndroidList = salesReturnMapper.getSaleAndroidList(pageQuery.build());
//            List<AndroidPdaDto> records = saleAndroidList.getRecords();
//            for (AndroidPdaDto entity : records) {
//                String unitName = remoteUnitService.getUnitDataByCode(entity.getMaterialUnit()).getData().getUnitName();
//                entity.setMaterialUnitDict(unitName);
//                entity.setStatusDict(statusMap.get(String.valueOf(entity.getStatus())));
//            }
//            return TableDataInfo.build(saleAndroidList);
//        } else if (number == 2) {
//            //获取单据状态字典数据
//            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "wip_completion_status");
//            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//            //完工入库
//            Page<AndroidPdaDto> wipCompletionAndroidManualList = wipCompletionMapper.getWipCompletionAndroidManualList(pageQuery.build());
//            List<AndroidPdaDto> records = wipCompletionAndroidManualList.getRecords();
//            for (AndroidPdaDto entity : records) {
//                String unitName = remoteUnitService.getUnitDataByCode(entity.getMaterialUnit()).getData().getUnitName();
//                entity.setMaterialUnitDict(unitName);
//                entity.setStatusDict(statusMap.get(String.valueOf(entity.getStatus())));
//            }
//            return TableDataInfo.build(wipCompletionAndroidManualList);
//        } else if (number == 4) {
//            //销售发货(动态根据表名和状态查出Pda列表)
//            Page<AndroidPdaDto> pickSaleAndroidList = pickingSaleMapper.getPickSaleAndroidList(pageQuery.build(), "picking_sale", "5", "6");
//            List<AndroidPdaDto> records = pickSaleAndroidList.getRecords();
//
//            //获取单据状态字典数据
//            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_sale_status");
//            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//            for (AndroidPdaDto record : records) {
//                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
//                record.setMaterialUnitDict(unitName);
//                record.setStatusDict(statusMap.get(record.getStatus() + ""));
//            }
//            return TableDataInfo.build(pickSaleAndroidList);
//        } else if (number == 5) {
//            //采购退货(动态根据表名和状态查出Pda列表)
//            Page<AndroidPdaDto> pickSaleAndroidList = pickingSaleMapper.getPickSaleAndroidCgList(pageQuery.build(), "picking_purchase", "5", "6");
//            List<AndroidPdaDto> records = pickSaleAndroidList.getRecords();
//
//            //获取单据状态字典数据
//            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_purchase_status");
//            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//            for (AndroidPdaDto record : records) {
//                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
//                record.setMaterialUnitDict(unitName);
//                record.setStatusDict(statusMap.get(record.getStatus() + ""));
//            }
//            return TableDataInfo.build(pickSaleAndroidList);
//        } else if (number == 6) {
//            //领料出库(动态根据表名和状态查出Pda列表)
//            Page<AndroidPdaDto> pickSaleAndroidList = pickingSaleMapper.getPickSaleAndroidList(pageQuery.build(), "stock_out_info", "2", "3");
//            List<AndroidPdaDto> records = pickSaleAndroidList.getRecords();
//
//            //获取单据状态字典数据
//            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "stock_out_info_status");
//            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//            for (AndroidPdaDto record : records) {
//                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
//                record.setMaterialUnitDict(unitName);
//                record.setStatusDict(statusMap.get(record.getStatus() + ""));
//            }
//            return TableDataInfo.build(pickSaleAndroidList);
//        } else if (number == 7) {
//            //其他出库(动态根据表名和状态查出Pda列表)
//            Page<AndroidPdaDto> pickSaleAndroidList = pickingSaleMapper.getPickSaleAndroidList(pageQuery.build(), "picking_rest", "1", "2");
//            List<AndroidPdaDto> records = pickSaleAndroidList.getRecords();
//
//            //获取单据状态字典数据
//            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_rest_status");
//            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//            for (AndroidPdaDto record : records) {
//                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
//                record.setMaterialUnitDict(unitName);
//                record.setStatusDict(statusMap.get(record.getStatus() + ""));
//            }
//            return TableDataInfo.build(pickSaleAndroidList);
//        } else {
//            List<AndroidPdaDto> objects = new ArrayList<>();
//            return TableDataInfo.build(objects);
//        }
    }

    /**
     * 手持pda 查看接口
     *
     * @param number
     * @return
     */
    @Override
    public AndroidPdaViewDto androidPdaView(int number, long id) {
        //状态
        List<SysDictData> typeArray = CacheUtils.get(CacheNames.SYS_DICT, "android_pda_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //采购入库列表
        if (number == 1) {
            AndroidPdaViewDto receiptViewAndroidById = purchaseReceiptMapper.getReceiptViewAndroidById(id);
            receiptViewAndroidById.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return receiptViewAndroidById;
        } else if (number == 2) {
            //完工入库
            AndroidPdaViewDto wipCompletionViewAndroidManualById = wipCompletionMapper.getWipCompletionViewAndroidManualById(id);
            wipCompletionViewAndroidManualById.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return wipCompletionViewAndroidManualById;
        } else if (number == 3) {
            //生产退料
            AndroidPdaViewDto productionByIdAndroid = productionMaterialReturnMapper.getProductionByIdAndroid(id);
            productionByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return productionByIdAndroid;
        } else if (number == 4) {
            //销售退货
            AndroidPdaViewDto saleByIdAndroid = salesReturnMapper.getSaleByIdAndroid(id);
            saleByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return saleByIdAndroid;
        } else if (number == 5) {
            //委外入库
            AndroidPdaViewDto subcontractByIdAndroid = subcontractReceiptMapper.getSubcontractByIdAndroid(id);
            subcontractByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return subcontractByIdAndroid;
        } else if (number == 6) {
            //其他入库
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getMiscellaneousByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else if (number == 7) {
            //生产领料
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getStockByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else if (number == 8) {
            //委外发货
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getOutsourceByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else if (number == 9) {
            //销售发货
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getSaleByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else if (number == 10) {
            //返工出库
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getCompleteByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else if (number == 11) {
            //采购退货
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getPurchaseByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else if (number == 12) {
            //委外退货
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getReturnByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else if (number == 13) {
            //其他出库
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getRestByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else {
            return null;
        }
//        //单位集合
//        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();
//
//        //采购入库
//        if (number == 1) {
//            AndroidPdaViewDto receiptViewAndroidById = purchaseReceiptMapper.getReceiptViewAndroidById(id);
//            receiptViewAndroidById.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
//            if (receiptViewAndroidById.getMaterialUnit() != null) {
//                receiptViewAndroidById.setUnitDict(unitByCodeToMap.get(receiptViewAndroidById.getMaterialUnit()).getUnitName());
//            }
//            return receiptViewAndroidById;
//        } else if (number == 2) {
//            //销售退货
//            AndroidPdaViewDto saleByIdAndroid = salesReturnMapper.getSaleByIdAndroid(id);
//            saleByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
//            if (saleByIdAndroid.getMaterialUnit() != null) {
//                saleByIdAndroid.setUnitDict(unitByCodeToMap.get(saleByIdAndroid.getMaterialUnit()).getUnitName());
//            }
//            return saleByIdAndroid;
//        } else if (number == 3) {
//            //完工入库
//            AndroidPdaViewDto wipCompletionViewAndroidManualById = wipCompletionMapper.getWipCompletionViewAndroidManualById(id);
//            wipCompletionViewAndroidManualById.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
//            if (wipCompletionViewAndroidManualById.getMaterialUnit() != null) {
//                wipCompletionViewAndroidManualById.setUnitDict(unitByCodeToMap.get(wipCompletionViewAndroidManualById.getMaterialUnit()).getUnitName());
//            }
//            return wipCompletionViewAndroidManualById;
//        } else if (number == 4) {
//            //销售发货
//            AndroidPdaViewDto pickSaleView = pickingSaleMapper.getPickSaleView("picking_sale", id);
//            //单据类型
//            pickSaleView.setWarehousingTypeDict("销售发货");
//            //单位
//            if (pickSaleView.getMaterialUnit() != null) {
//                pickSaleView.setUnitDict(unitByCodeToMap.get(pickSaleView.getMaterialUnit()).getUnitName());
//            }
//            //拣货提醒
//            String combinationName = pickingSaleService.point(id).getCombinationName();
//            pickSaleView.setCombinationName(combinationName);
//            return pickSaleView;
//        } else if (number == 5) {
//            //采购退货
//            AndroidPdaViewDto pickSaleView = pickingSaleMapper.getPickSaleView("picking_purchase", id);
//            //单据类型
//            pickSaleView.setWarehousingTypeDict("采购退货");
//            //单位
//            if (pickSaleView.getMaterialUnit() != null) {
//                pickSaleView.setUnitDict(unitByCodeToMap.get(pickSaleView.getMaterialUnit()).getUnitName());
//            }
//            //拣货提醒
//            String combinationName = pickingPurchaseService.point(id).getCombinationName();
//            pickSaleView.setCombinationName(combinationName);
//            return pickSaleView;
//        } else if (number == 6) {
//            //领料出库
//            AndroidPdaViewDto pickSaleView = pickingSaleMapper.getPickSaleView("stock_out_info", id);
//            //单据类型
//            pickSaleView.setWarehousingTypeDict("领料出库");
//            //单位
//            if (pickSaleView.getMaterialUnit() != null) {
//                pickSaleView.setUnitDict(unitByCodeToMap.get(pickSaleView.getMaterialUnit()).getUnitName());
//            }
//            //拣货提醒
//            String combinationName = stockOutInfoService.point(id).getCombinationName();
//            pickSaleView.setCombinationName(combinationName);
//            return pickSaleView;
//        } else if (number == 7) {
//            //其他出库
//            AndroidPdaViewDto pickSaleView = pickingSaleMapper.getPickSaleView("picking_rest", id);
//            //单据类型
//            pickSaleView.setWarehousingTypeDict("其他出库");
//            //单位
//            if (pickSaleView.getMaterialUnit() != null) {
//                pickSaleView.setUnitDict(unitByCodeToMap.get(pickSaleView.getMaterialUnit()).getUnitName());
//            }
//            //拣货提醒
//            String combinationName = pickingRestService.point(id).getCombinationName();
//            pickSaleView.setCombinationName(combinationName);
//            return pickSaleView;
//        } else {
//            return null;
//        }
    }


    /**
     * 手持pda 拣货撤销列表
     *
     * @param number
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TableDataInfo<AndroidPdaDto> pickCancellationList(PageQuery pageQuery, int number) {
        Long deptId = LoginHelper.getDeptId();
        if (number == 1) {
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "production_material_return_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            //生产退料
            Page<AndroidPdaDto> purchaseReceiptCancellationList = productionMaterialReturnMapper.getProductionpickCancellationList(deptId, pageQuery.build());
            List<AndroidPdaDto> records = purchaseReceiptCancellationList.getRecords();
            for (AndroidPdaDto entity : records) {
                entity.setMaterialUnitDict(remoteUnitService.getUnitDataByCode(entity.getMaterialUnit()).getData().getUnitName());
                entity.setStatusDict(statusMap.get(String.valueOf(entity.getStatus())));
            }
            return TableDataInfo.build(purchaseReceiptCancellationList);
        } else if (number == 2) {
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_return_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //销售退货
            Page<AndroidPdaDto> saleAndroidpickCancellationList = salesReturnMapper.getSaleAndroidpickCancellationList(pageQuery.build());
            List<AndroidPdaDto> records = saleAndroidpickCancellationList.getRecords();
            for (AndroidPdaDto entity : records) {
                entity.setMaterialUnitDict(remoteUnitService.getUnitDataByCode(entity.getMaterialUnit()).getData().getUnitName());
                entity.setStatusDict(statusMap.get(String.valueOf(entity.getStatus())));
            }
            return TableDataInfo.build(saleAndroidpickCancellationList);
        } else if (number == 3) {
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "wip_completion_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            //完工入库
            Page<AndroidPdaDto> wipCompletionAndroidManualpickCancellationList = wipCompletionMapper.getWipCompletionAndroidManualpickCancellationList(pageQuery.build());
            List<AndroidPdaDto> records = wipCompletionAndroidManualpickCancellationList.getRecords();
            for (AndroidPdaDto entity : records) {
                entity.setMaterialUnitDict(remoteUnitService.getUnitDataByCode(entity.getMaterialUnit()).getData().getUnitName());
                entity.setStatusDict(statusMap.get(String.valueOf(entity.getStatus())));
            }
            return TableDataInfo.build(wipCompletionAndroidManualpickCancellationList);
        } else if (number == 4) {
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "miscellaneous_receipt_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            //其他入库
            Page<AndroidPdaDto> wipCompletionAndroidManualpickCancellationList = miscellaneousReceiptMapper.getMiscellaneousAndroidpickCancellationList(deptId, pageQuery.build());
            List<AndroidPdaDto> records = wipCompletionAndroidManualpickCancellationList.getRecords();
            for (AndroidPdaDto entity : records) {
                entity.setMaterialUnitDict(remoteUnitService.getUnitDataByCode(entity.getMaterialUnit()).getData().getUnitName());
                entity.setStatusDict(statusMap.get(String.valueOf(entity.getStatus())));
            }
            return TableDataInfo.build(wipCompletionAndroidManualpickCancellationList);
        } else if (number == 5) {
            //生产领料
            Page<AndroidPdaDto> stockOutInfoList = stockOutInfoMapper.getCancelPda(deptId, pageQuery.build());
            List<AndroidPdaDto> records = stockOutInfoList.getRecords();

            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "stock_out_info_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto record : records) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(stockOutInfoList);
        } else if (number == 6) {
            //委外发货
            Page<AndroidPdaDto> pickingOutsourceList = pickingOutsourceMapper.getCancelPda(deptId, pageQuery.build());
            List<AndroidPdaDto> records = pickingOutsourceList.getRecords();

            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_outsource_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto record : records) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(pickingOutsourceList);
        } else if (number == 7) {
            //销售发货
            Page<AndroidPdaDto> pickSaleAndroidList = pickingSaleMapper.getCancelPda(deptId, pageQuery.build());
            List<AndroidPdaDto> records = pickSaleAndroidList.getRecords();

            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_sale_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto record : records) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(pickSaleAndroidList);
        } else if (number == 8) {
            //其他出库(动态根据表名和状态查出Pda列表)
            Page<AndroidPdaDto> pickSaleAndroidList = pickingRestMapper.getCancelPda(deptId, pageQuery.build());
            List<AndroidPdaDto> records = pickSaleAndroidList.getRecords();

            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_rest_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidPdaDto record : records) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(pickSaleAndroidList);
        } else {
            List<AndroidPdaDto> objects = new ArrayList<>();
            return TableDataInfo.build(objects);
        }
    }

    /**
     * 手持pda 拣货完成
     *
     * @param completionPickingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completionPickingAndroid(CompletionPickingVo completionPickingVo) throws Exception {
        PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
        pickingRestDbVo.setId(completionPickingVo.getId());
        if (completionPickingVo.getNumber() == 1) {
            //采购入库
            return pickingCompleted(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 2) {
            //销售退货
            return salesReturnService.pickingCompleted(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 3) {
            //完工入库
            return wipCompletionService.pickingCompleted(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 7) {
            //生产领料
            return stockOutInfoService.finishProduction(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 8) {
            //委外发货
            return pickingOutsourceService.finishProduction(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 9) {
            //销售发货
            return pickingSaleService.finishProduction(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 10) {
            //返工出库
            return pickingCompleteService.finishProduction(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 11) {
            //采购退货
            return pickingPurchaseService.subcontractingPurchase(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 12) {
            //委外退货
            return pickingReturnsService.subcontractingPicking(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 13) {
            //其他出库
            return pickingRestService.pickingRestCompleted(completionPickingVo.getId());
        } else {
            return false;
        }

    }

    /**
     * 手持pda 拣货撤销
     *
     * @param completionPickingVo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickCancellationAndroid(CompletionPickingVo completionPickingVo) {
        PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
        pickingRestDbVo.setId(completionPickingVo.getId());
        if (completionPickingVo.getNumber() == 1) {
            //生产退料
            return productionMaterialReturnService.pickingCancellation(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 2) {
            //销售退货
            return salesReturnService.pickingCancellation(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 3) {
            //完工入库
            return wipCompletionService.pickingCancellation(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 4) {
            //其他入库
            return miscellaneousReceiptService.pickingCancellation(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 5) {
            return stockOutInfoService.repealProduction(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 6) {
            return pickingOutsourceService.repealProduction(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 7) {
            return pickingSaleService.repealProduction(completionPickingVo.getId());
        } else if (completionPickingVo.getNumber() == 8) {
            return pickingRestService.pickingRestRepeal(completionPickingVo.getId());
        } else {
            return false;
        }

    }

    /**
     * 手持pda 交接列表
     *
     * @param number
     * @return
     */
    @Override
    public TableDataInfo<AndroidHandoverPdaDto> androidHandoverList(int number, PageQuery pageQuery) {
        Long deptId = LoginHelper.getDeptId();
        if (number == 1) {
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "production_material_return_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            //生产退料
            Page<AndroidHandoverPdaDto> androidHandoverList = productionMaterialReturnMapper.getAndroidHandoverList(deptId, pageQuery.build());
            ;
            List<AndroidHandoverPdaDto> records = androidHandoverList.getRecords();
            for (AndroidHandoverPdaDto record : records) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 2) {
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_return_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            //销售退货
            Page<AndroidHandoverPdaDto> androidHandoverList = salesReturnMapper.getAndroidHandoverList(pageQuery.build());
            List<AndroidHandoverPdaDto> records = androidHandoverList.getRecords();
            for (AndroidHandoverPdaDto record : records) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 3) {
            //获取单据状态字典数据
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "miscellaneous_receipt_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            //其他入库
            Page<AndroidHandoverPdaDto> androidHandoverList = miscellaneousReceiptMapper.getAndroidHandoverList(deptId, pageQuery.build());
            List<AndroidHandoverPdaDto> records = androidHandoverList.getRecords();
            for (AndroidHandoverPdaDto record : records) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 4) {
            //领料出库
            Page<AndroidHandoverPdaDto> androidHandoverList = stockOutInfoMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "stock_out_info_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 6) {
            //销售发货
            Page<AndroidHandoverPdaDto> androidHandoverList = pickingSaleMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_sale_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 5) {
            //委外发货
            Page<AndroidHandoverPdaDto> androidHandoverList = pickingOutsourceMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_outsource_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 7) {
            //返工出库
            Page<AndroidHandoverPdaDto> androidHandoverList = pickingCompleteMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_complete_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 8) {
            //采购退货
            Page<AndroidHandoverPdaDto> androidHandoverList = pickingPurchaseMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_purchase_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 9) {
            //委外退货
            Page<AndroidHandoverPdaDto> androidHandoverList = pickingReturnsMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_returns_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 10) {
            //其他出库
            Page<AndroidHandoverPdaDto> androidHandoverList = pickingRestMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "picking_rest_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else if (number == 11) {
            //调拨单
            Page<AndroidHandoverPdaDto> androidHandoverList = allotManagementMapper.getHandoverList(deptId, pageQuery.build());
            List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "allot_management_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (AndroidHandoverPdaDto record : androidHandoverList.getRecords()) {
                String unitName = remoteUnitService.getUnitDataByCode(record.getMaterialUnit()).getData().getUnitName();
                record.setMaterialUnitDict(unitName);
                record.setStatusDict(statusMap.get(record.getStatus() + ""));
            }
            return TableDataInfo.build(androidHandoverList);
        } else {
            List<AndroidHandoverPdaDto> objects = new ArrayList<>();
            return TableDataInfo.build(objects);
        }

    }

    /**
     * 手持pda 交接详情
     *
     * @param number
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AndroidHandoverPdaDto androidHandoverView(int number, Long id) {

        List<SysDictData> typeArray = CacheUtils.get(CacheNames.SYS_DICT, "android_pda_handover_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //交接方式
        List<SysDictData> methodArray = CacheUtils.get(CacheNames.SYS_DICT, "sys_handover_method");
        Map<String, String> methodMap = methodArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        if (number == 1) {
            //生产退料
            AndroidHandoverPdaDto androidHandoverView = productionMaterialReturnMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "生产退料";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 2) {
            //销售退货
            AndroidHandoverPdaDto androidHandoverView = salesReturnMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "销售退货";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 3) {
            //其他入库
            AndroidHandoverPdaDto androidHandoverView = miscellaneousReceiptMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "其他入库";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 4) {
            //领料出库
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id, "stock_out_info");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "生产领料";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 5) {
            //委外出库
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id, "picking_outsource");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "委外发货";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 6) {
            //销售发货
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id, "picking_sale");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "销售发货";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 7) {
            //返工出库
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id, "picking_complete");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "返工出库";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 8) {
            //采购退货
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id, "picking_purchase");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "采购退货";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 9) {
            //委外退货
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id, "picking_returns");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "委外退货";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 10) {
            //其他出库
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id, "picking_rest");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "其他出库";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else if (number == 11) {
            //其他出库
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverAllotView(id, "allot_management");
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "调拨管理";
            Long idByMenuName = remoteMenuService.getIdByMenuName(menuName);
            SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(idByMenuName);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            //单位
            String unitName = remoteUnitService.getUnitDataByCode(androidHandoverView.getMaterialUnit()).getData().getUnitName();
            androidHandoverView.setMaterialUnitDict(unitName);
            return androidHandoverView;
        } else {
            return null;
        }
    }

    /**
     * 手持pda 交接
     *
     * @param androidHandoverVo
     * @return
     */
    @Override
    public PickingRestHandoverDto androidHandover(AndroidHandoverVo androidHandoverVo) {
        //生产退料交接
        if (androidHandoverVo.getNumber() == 1) {
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return productionMaterialReturnService.handover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 2) {
            //销售退货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return salesReturnService.handover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 3) {
            //其它入库
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return miscellaneousReceiptService.handover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 8) {
            //采购退货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingPurchaseService.purchaseHandover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 4) {
            //领料出库
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return stockOutInfoService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 10) {
            //其他出库
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingRestService.pickingRestHandover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 5) {
            //委外发货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingOutsourceService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 6) {
            //销售发货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingSaleService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 7) {
            //反攻出库
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingCompleteService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 9) {
            //委外退货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingReturnsService.overProductionReturns(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 11) {
            //调拨
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return allotManagementService.overAllot(pickingRestDbVo);
        } else {
            return new PickingRestHandoverDto();
        }
    }

    /**
     * 财务模块修改采购入库发票数量
     *
     * @param updateInvoicedQuantityVo
     * @return
     */
    @Override
    public boolean updateInvoicedQuantity(UpdateInvoicedQuantityVo updateInvoicedQuantityVo) {
        List<QuantityDataVo> list = updateInvoicedQuantityVo.getList();
        int i = 0;
        for (QuantityDataVo entity : list) {
            if ("采购入库".equals(entity.getDocumentType())) {
                //修改对应的数据
                PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectOne(new QueryWrapper<PurchaseReceipt>().lambda()
                    .eq(PurchaseReceipt::getReceiptNo, entity.getReceiptNumber()));
                if (entity.getQuantity() != null) {
                    if (purchaseReceipt.getInvoicedQuantity() != null) {
                        BigDecimal add = new BigDecimal(purchaseReceipt.getInvoicedQuantity()).add(new BigDecimal(entity.getQuantity()));
                        purchaseReceipt.setInvoicedQuantity(add.toString());
                    } else {
                        purchaseReceipt.setInvoicedQuantity(entity.getQuantity());
                    }
                }

                //核销金额
                if (entity.getApprovedAmount() != null) {
                    if (purchaseReceipt.getApprovedAmount() != null) {
                        BigDecimal add = new BigDecimal(String.valueOf(purchaseReceipt.getApprovedAmount())).add(new BigDecimal(String.valueOf(entity.getApprovedAmount())));
                        purchaseReceipt.setApprovedAmount(add);
                    } else {
                        purchaseReceipt.setApprovedAmount(entity.getApprovedAmount());
                    }
                }

                i = purchaseReceiptMapper.updateById(purchaseReceipt);
            }
            if ("销售退货".equals(entity.getDocumentType())) {
                //修改对应的数据
                SalesReturn salesReturn = salesReturnMapper.selectOne(new QueryWrapper<SalesReturn>().lambda()
                    .eq(SalesReturn::getReceiptNo, entity.getReceiptNumber()));
                if (entity.getQuantity() != null) {
                    if (salesReturn.getInvoicedQuantity() != null) {
                        BigDecimal add = new BigDecimal(salesReturn.getInvoicedQuantity()).add(new BigDecimal(entity.getQuantity()));
                        salesReturn.setInvoicedQuantity(add.toString());
                    } else {
                        salesReturn.setInvoicedQuantity(entity.getQuantity());
                    }
                }

                //核销金额
                if (entity.getApprovedAmount() != null) {
                    if (salesReturn.getApprovedAmount() != null) {
                        BigDecimal add = new BigDecimal(String.valueOf(salesReturn.getApprovedAmount())).add(new BigDecimal(String.valueOf(entity.getApprovedAmount())));
                        salesReturn.setApprovedAmount(Double.parseDouble(add.toString()));
                    } else {
                        salesReturn.setApprovedAmount(Double.parseDouble(String.valueOf(entity.getApprovedAmount())));
                    }
                }

                i = salesReturnMapper.updateById(salesReturn);
            }
            if ("销售发货".equals(entity.getDocumentType())) {
                //修改对应的数据
                PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>().lambda()
                    .eq(PickingSale::getWodDocNum, entity.getReceiptNumber()));
                if (entity.getQuantity() != null) {
                    if (pickingSale.getInvoicedQuantity() != null) {
                        BigDecimal add = new BigDecimal(pickingSale.getInvoicedQuantity()).add(new BigDecimal(entity.getQuantity()));
                        pickingSale.setInvoicedQuantity(add.toString());
                    } else {
                        pickingSale.setInvoicedQuantity(entity.getQuantity());
                    }
                }

                //核销金额
                if (entity.getApprovedAmount() != null) {
                    if (pickingSale.getApprovedAmount() != null) {
                        BigDecimal add = new BigDecimal(String.valueOf(pickingSale.getApprovedAmount())).add(new BigDecimal(String.valueOf(entity.getApprovedAmount())));
                        pickingSale.setApprovedAmount(Double.parseDouble(add.toString()));
                    } else {
                        pickingSale.setApprovedAmount(Double.parseDouble(String.valueOf(entity.getApprovedAmount())));
                    }
                }

                i = pickingSaleMapper.updateById(pickingSale);
            }
            if ("采购退货".equals(entity.getDocumentType())) {
                //修改对应的数据
                PickingPurchase pickingPurchase = pickingPurchaseMapper.selectOne(new QueryWrapper<PickingPurchase>().lambda()
                    .eq(PickingPurchase::getWodDocNum, entity.getReceiptNumber()));
                if (entity.getQuantity() != null) {
                    if (pickingPurchase.getInvoicedQuantity() != null) {
                        BigDecimal add = new BigDecimal(pickingPurchase.getInvoicedQuantity()).add(new BigDecimal(entity.getQuantity()));
                        pickingPurchase.setInvoicedQuantity(add.toString());
                    } else {
                        pickingPurchase.setInvoicedQuantity(entity.getQuantity());
                    }
                }

                //核销金额
                if (entity.getApprovedAmount() != null) {
                    if (pickingPurchase.getApprovedAmount() != null) {
                        BigDecimal add = new BigDecimal(String.valueOf(pickingPurchase.getApprovedAmount())).add(new BigDecimal(String.valueOf(entity.getApprovedAmount())));
                        pickingPurchase.setApprovedAmount(Double.parseDouble(add.toString()));
                    } else {
                        pickingPurchase.setApprovedAmount(Double.parseDouble(String.valueOf(entity.getApprovedAmount())));
                    }
                }

                i = pickingPurchaseMapper.updateById(pickingPurchase);
            }
        }
        return i > 0;
    }

    /**
     * 根据供应商编码获取该供应商总欠款
     *
     * @param supplierCode
     * @return
     */
    @Override
    public String getBalance(String supplierCode) {

        List<PurchaseReceipt> purchaseReceipts = purchaseReceiptMapper.selectList(new QueryWrapper<PurchaseReceipt>().lambda()
            .eq(PurchaseReceipt::getSupplierCode, supplierCode));
        BigDecimal bigDecimal = new BigDecimal("0");
        BigDecimal bigDecimal1 = new BigDecimal("0");
        if (purchaseReceipts.size() > 0) {
            for (PurchaseReceipt entity : purchaseReceipts) {
                //单价
                BigDecimal unitPrice = entity.getUnitPrice();
                //数量
                String s = String.valueOf(entity.getPlannedWeight());
                BigDecimal multiply = new BigDecimal(String.valueOf(unitPrice)).multiply(new BigDecimal(s));
                bigDecimal = bigDecimal.add(multiply);
                //已核销金额
                if (entity.getApprovedAmount() != null) {
                    bigDecimal1 = bigDecimal1.add(new BigDecimal(String.valueOf(entity.getApprovedAmount())));
                }
            }
            return bigDecimal.subtract(bigDecimal1).toString();
        }
        return bigDecimal.toString();
    }

    /**
     * 财务-核销单（根据供应商编码获取对应数据）
     *
     * @param
     * @return
     */
    @Override
    public TableDataInfo<ImparityDto> getDataByCode(GetDataByCodeVo getDataByCodeVo, PageQuery pageQuery) {

        //根据供应商编码获取数据
        Page<ImparityDto> imparityDtos = purchaseReceiptMapper.selectDataBySupplierCode(getDataByCodeVo, pageQuery.build());
        List<ImparityDto> records = imparityDtos.getRecords();
        if (records.size() > 0) {
            for (ImparityDto entity : records) {
                //单据类型
                entity.setReceiptType(DocumentTypeEnum.getValue(Integer.parseInt(entity.getReceiptType())));
                //单据金额
                BigDecimal multiply = new BigDecimal(String.valueOf(entity.getUnitPrice())).multiply(new BigDecimal(String.valueOf(entity.getPlannedWeight())));
                entity.setDocumentAmount(multiply.toString());
                //已核销金额
                entity.setApprovedAmount(entity.getApprovedAmount());
                //未核销金额
                if (entity.getApprovedAmount() == null) {
                    entity.setNotApprovedAmount(multiply.toString());
                } else {
                    BigDecimal subtract = multiply.subtract(new BigDecimal(entity.getApprovedAmount()));
                    entity.setNotApprovedAmount(subtract.toString());
                }
            }
            return TableDataInfo.build(imparityDtos);
        }
        return null;
    }

    /**
     * 采购订单跟踪查询
     *
     * @return PurchaseOrderTrackDto
     */
    @Override
    public TableDataInfo<PurchaseOrderTrackDto> purchaseOrderTrackList(PurchaseOrderTraceVo purchaseOrderTraceVo) {
        List<PurchaseOrderTrackDto> purchaseOrderTrackList = purchaseReceiptMapper.getPurchaseOrderTrackList(purchaseOrderTraceVo);
        return TableDataInfo.build(purchaseOrderTrackList);
    }

    /**
     * 采购统计 - 采购汇总表物料统计
     *
     * @param materialStatListVo
     * @return
     */
    @Override
    public TableDataInfo<MaterialStatListDto> materialStatList(MaterialStatListVo materialStatListVo, PageQuery pageQuery) throws Exception {
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();
        //多单位转换map
        Map<Long, String> unitToMap = remoteUnitService.getUnitToMap();
        if (materialStatListVo.getStatisticalMethod() == 1) {
            //物料统计
            List<MaterialStatListDto> records = purchaseReceiptMapper.getMaterialStatList(materialStatListVo);
            //排除掉没有入库的数据
            List<MaterialStatListDto> collect1 = records.stream().filter(entity -> entity.getWarehouseName() != null).collect(Collectors.toList());
            //根据物料编码和仓库名称进行分组
            Map<String, Map<String, List<MaterialStatListDto>>> infoMap = collect1.stream()
                .collect(Collectors.groupingBy(MaterialStatListDto::getMaterialCode, Collectors.groupingBy(x -> Optional.ofNullable(x.getWarehouseName()).orElse("0"))));

            List<MaterialStatListDto> objects = new ArrayList<>();
            for (Map.Entry<String, Map<String, List<MaterialStatListDto>>> entry : infoMap.entrySet()) {

                Map<String, List<MaterialStatListDto>> value = entry.getValue();

                for (Map.Entry<String, List<MaterialStatListDto>> value1 : value.entrySet()) {

                    MaterialStatListDto materialStatListDto = new MaterialStatListDto();
                    //物料编码
                    materialStatListDto.setMaterialCode(entry.getKey());
                    //仓库
                    materialStatListDto.setWarehouseName(value1.getKey());
                    List<MaterialStatListDto> value2 = value1.getValue();
                    //获取单价之和
                    BigDecimal bigDecimal = new BigDecimal("0");
                    //获取单位数量之和
                    BigDecimal bigDecimal1 = new BigDecimal("0");
                    //采购金额
                    BigDecimal bigDecimal2 = new BigDecimal("0");
                    for (MaterialStatListDto entity : value2) {
                        if (entity.getUnitPrice() != null) {
                            bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(entity.getUnitPrice())));
                        }

                        if (entity.getActualQuantity() != null) {
                            bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getActualQuantity()));
                        }
                        BigDecimal multiply = new BigDecimal(String.valueOf(entity.getUnitPrice())).multiply(new BigDecimal(entity.getActualQuantity()));
                        bigDecimal2 = bigDecimal2.add(multiply);
                    }
                    //辅助属性
                    List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + value2.get(0).getTenantId(), String.valueOf(value2.get(0).getMaterialId()));
                    materialStatListDto.setAuxiliaryAttribute(statsArray);
                    //类别
                    if (value2.get(0).getMaterialCategory() == 1) {
                        materialStatListDto.setMaterialCategoryDict("原料");
                    } else {
                        materialStatListDto.setMaterialCategoryDict("成品");
                    }
                    //采购金额
                    materialStatListDto.setPurchaseAmount(bigDecimal2);

                    //多单位转换获取单位数量
                    Long unit = value2.get(0).getUnit();
                    String s = unitToMap.get(unit);
                    BigDecimal multiply = new BigDecimal("0");
                    if (s != null) {
                        multiply = bigDecimal1.multiply(new BigDecimal(s));
                    } else {
                        multiply = bigDecimal1;
                    }
                    materialStatListDto.setMaterialTotal(multiply.toString());
                    //单价
                    if (multiply.compareTo(BigDecimal.ZERO) != 0) {
//                        BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
                        BigDecimal divide = bigDecimal2.divide(new BigDecimal(String.valueOf(multiply)), 2);
                        materialStatListDto.setUnitPrice(Double.parseDouble(divide.toString()));
                    }
                    //物料名称
                    materialStatListDto.setMaterialName(value2.get(0).getMaterialName());
                    //物料类别
                    materialStatListDto.setCodingRules(value2.get(0).getCodingRules());
                    //规格
                    materialStatListDto.setMaterialSpec(value2.get(0).getMaterialSpec());

                    MaterialUnitDto unitByCode = unitByCodeToMap.get(entry.getKey());
//                    MaterialUnitDto unitByCode = remoteUnitService.getUnitByCode(entry.getKey());
                    if (value2.get(0).getMaterialMoreUnit() != null) {
                        SysAuxiliaryUnitDateDetailResultDto materialUnitById = remoteInventoryInquiryService.getMaterialUnitById(Long.valueOf(value2.get(0).getMaterialMoreUnit()), value2.get(0).getMaterialId());
                        // 多计量单位名称

                        // 获取逗号前的基础单位
                        int str = materialUnitById.getAuxiliaryUnitName().indexOf(',');
                        String substring = materialUnitById.getAuxiliaryUnitName().substring(0, str);

                        long c = (long) (Double.parseDouble(String.valueOf(multiply)));
                        MaterialUnitDto materialUnitDto = remoteInventoryInquiryService.selectMaterialUnitList(Long.valueOf(value2.get(0).getMaterialMoreUnit()), c);
                        //多单位
                        materialStatListDto.setMaterialMoreUnit(materialUnitById.getAuxiliaryUnitName());

                        //多单位数量
                        materialStatListDto.setMaterialMoreUnitNumber(materialUnitDto.getUnitName());
                        //单位
                        materialStatListDto.setUnitDict(substring);
                    } else {
                        //单位
                        materialStatListDto.setUnitDict(unitByCode.getUnitName());
                    }

                    objects.add(materialStatListDto);
                }
            }
            //手动分页
            Page<MaterialStatListDto> page = new Page<>();
            List<MaterialStatListDto> collect = objects.stream().skip((long) (pageQuery.getPageNum() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());
            page.setRecords(collect);
            page.setTotal(objects.size());
            return TableDataInfo.build(page);
        } else {
            //供应商统计
            List<MaterialStatListDto> records = purchaseReceiptMapper.getMaterialStatSupplierList(materialStatListVo);
            //根据供应商编码、物料编码、仓库名称进行分组
            Map<String, Map<String, Map<String, List<MaterialStatListDto>>>> styleMap = records.stream()
                .collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getSupplierNum()).orElse("0"),
                    Collectors.groupingBy(MaterialStatListDto::getMaterialCode,
                        Collectors.groupingBy(x -> Optional.ofNullable(x.getWarehouseName()).orElse("0")))));

            List<MaterialStatListDto> objects = new ArrayList<>();
            for (Map.Entry<String, Map<String, Map<String, List<MaterialStatListDto>>>> entry : styleMap.entrySet()) {
                Map<String, Map<String, List<MaterialStatListDto>>> value = entry.getValue();

                for (Map.Entry<String, Map<String, List<MaterialStatListDto>>> entry1 : value.entrySet()) {
                    Map<String, List<MaterialStatListDto>> value1 = entry1.getValue();
                    for (Map.Entry<String, List<MaterialStatListDto>> value2 : value1.entrySet()) {
                        MaterialStatListDto materialStatListDto = new MaterialStatListDto();
                        //物料编码
                        materialStatListDto.setMaterialCode(entry1.getKey());
                        //仓库
                        materialStatListDto.setWarehouseName(value2.getKey());
                        List<MaterialStatListDto> value3 = value2.getValue();
                        //获取单价之和
                        BigDecimal bigDecimal = new BigDecimal("0");
                        //获取单位数量之和
                        BigDecimal bigDecimal1 = new BigDecimal("0");
                        //采购金额
                        BigDecimal bigDecimal2 = new BigDecimal("0");
                        for (MaterialStatListDto entity : value3) {
                            if (entity.getUnitPrice() != null) {
                                bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(entity.getUnitPrice())));
                            }

                            if (entity.getActualQuantity() != null) {
                                bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getActualQuantity()));
                            }
                            BigDecimal multiply = new BigDecimal(String.valueOf(entity.getUnitPrice())).multiply(new BigDecimal(entity.getActualQuantity()));
                            bigDecimal2 = bigDecimal2.add(multiply);
                        }
                        //辅助属性
                        List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + value3.get(0).getTenantId(), String.valueOf(value3.get(0).getMaterialId()));
                        materialStatListDto.setAuxiliaryAttribute(statsArray);
                        //类别
                        if (value3.get(0).getMaterialCategory() == 1) {
                            materialStatListDto.setMaterialCategoryDict("原料");
                        } else {
                            materialStatListDto.setMaterialCategoryDict("成品");
                        }
                        //采购金额
                        materialStatListDto.setPurchaseAmount(bigDecimal2);
                        //多单位转换获取单位数量
                        Long unit = value3.get(0).getUnit();
                        String s = unitToMap.get(unit);
                        BigDecimal multiply = new BigDecimal("0");
                        if (s != null) {
                            multiply = bigDecimal1.multiply(new BigDecimal(s));
                        } else {
                            multiply = bigDecimal1;
                        }
                        materialStatListDto.setMaterialTotal(multiply.toString());
                        //单价
                        if (multiply.compareTo(BigDecimal.ZERO) != 0) {
//                            BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
                            BigDecimal divide = bigDecimal2.divide(new BigDecimal(String.valueOf(multiply)), 2);
                            materialStatListDto.setUnitPrice(Double.parseDouble(divide.toString()));
                        }
                        //物料名称
                        materialStatListDto.setMaterialName(value3.get(0).getMaterialName());
                        //物料类别
                        materialStatListDto.setCodingRules(value3.get(0).getCodingRules());
                        //规格
                        materialStatListDto.setMaterialSpec(value3.get(0).getMaterialSpec());

                        MaterialUnitDto unitByCode = unitByCodeToMap.get(entry1.getKey());
//                        MaterialUnitDto unitByCode = remoteUnitService.getUnitByCode(entry.getKey());
                        if (value3.get(0).getMaterialMoreUnit() != null) {
                            SysAuxiliaryUnitDateDetailResultDto materialUnitById = remoteInventoryInquiryService.getMaterialUnitById(Long.valueOf(value3.get(0).getMaterialMoreUnit()), value3.get(0).getMaterialId());
                            // 多计量单位名称

                            // 获取逗号前的基础单位
                            int str = materialUnitById.getAuxiliaryUnitName().indexOf(',');
                            String substring = materialUnitById.getAuxiliaryUnitName().substring(0, str);
                            long c = (long) (Double.parseDouble(String.valueOf(multiply)));
                            MaterialUnitDto materialUnitDto = remoteInventoryInquiryService.selectMaterialUnitList(Long.valueOf(value3.get(0).getMaterialMoreUnit()), c);
                            //多单位
                            materialStatListDto.setMaterialMoreUnit(materialUnitById.getAuxiliaryUnitName());

                            //多单位数量
                            materialStatListDto.setMaterialMoreUnitNumber(materialUnitDto.getUnitName());
                            //单位
                            materialStatListDto.setUnitDict(substring);
                        } else {
                            //单位
                            materialStatListDto.setUnitDict(unitByCode.getUnitName());
                        }
                        //供应商编码
                        materialStatListDto.setSupplierNum(value3.get(0).getSupplierNum());
                        //供应商名称
                        materialStatListDto.setSupplierName(value3.get(0).getSupplierName());

                        objects.add(materialStatListDto);
                    }
                }
            }
            //手动分页
            Page<MaterialStatListDto> page = new Page<>();
            List<MaterialStatListDto> collect = objects.stream().skip((long) (pageQuery.getPageNum() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());
            page.setRecords(collect);
            page.setTotal(objects.size());
            return TableDataInfo.build(page);


//            for (MaterialStatListDto entity : records) {
//                //辅助属性
//                List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
//                entity.setAuxiliaryAttribute(statsArray);
//                //类别
//                if (entity.getMaterialCategory() == 1) {
//                    entity.setMaterialCategoryDict("原料");
//                } else {
//                    entity.setMaterialCategoryDict("成品");
//                }
//                //采购金额
//                if (entity.getUnitPrice() != null) {
//                    BigDecimal multiply = new BigDecimal(String.valueOf(entity.getUnitPrice())).multiply(new BigDecimal(String.valueOf(entity.getMaterialTotal())));
//                    entity.setPurchaseAmount(multiply);
//                }
//                MaterialUnitDto unitByCode = remoteUnitService.getUnitByCode(entity.getMaterialCode());
//                //多单位
//                entity.setMaterialMoreUnit(unitByCode.getAuxiliaryUnit());
//                //多单位数量
//                entity.setMaterialMoreUnitNumber(getMoreUnit(String.valueOf(entity.getMaterialTotal()), unitByCode));
//                //单位
//                entity.setUnitDict(unitByCode.getUnitName());
//                //供应商编码
//                entity.setSupplierNum(entity.getSupplierNum());
//                //供应商名称
//                entity.setSupplierName(entity.getSupplierName());
//            }
//            return TableDataInfo.build(records);
        }

    }

    /**
     * 财务-核销单 通过获取未全部核销的采购入库单、采购退货单、其他支出单数据
     */
    @Override
    public TableDataInfo<ImparityDto> getNoVerificationList(GetDataByCodeVo getDataByCodeVo, PageQuery pageQuery) {
        //采购入库单
        List<ImparityDto> purchaseReceiptList = purchaseReceiptMapper.getNoVerificationList(getDataByCodeVo);
        //采购退货单
        List<ImparityDto> pickingPurchaseList = pickingPurchaseMapper.getNoVerificationList(getDataByCodeVo);
        //其他支出单数据
        GetDataByCodeGoodsVo getDataByCodeGoodsVo = new GetDataByCodeGoodsVo();
        getDataByCodeGoodsVo.setSupplierCode(getDataByCodeVo.getSupplierCode());
        getDataByCodeGoodsVo.setCreateTime(getDataByCodeVo.getCreateTime());
        getDataByCodeGoodsVo.setReceiptNumber(getDataByCodeVo.getReceiptNumber());
        List<ImparityGoodsDto> disburseList = remoteGoodsDisburseService.getNoVerificationList(getDataByCodeGoodsVo);
        List<ImparityDto> resultList = new ArrayList<>();
        for (ImparityGoodsDto entity : disburseList) {
            ImparityDto imparityDto = new ImparityDto();
            BeanUtils.copyProperties(entity, imparityDto);
            resultList.add(imparityDto);
        }
        resultList.addAll(purchaseReceiptList);
        resultList.addAll(pickingPurchaseList);
        //手动分页
        Page<ImparityDto> page = new Page<>();
        List<ImparityDto> collect = resultList.stream().skip((long) (pageQuery.getPageNum() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());
        page.setRecords(collect);
        page.setTotal(resultList.size());
        return TableDataInfo.build(page);

    }

    /**
     * 查询仓库单据数据（结账反结账使用）
     */
    @Override
    public ClosingDocumentDto closingCounterClosingDocument(String time) {
        ClosingDocumentDto closingDocumentDto = new ClosingDocumentDto();
        //领料出库(没有强管控，因为没有审核)
        List<StockOutInfoDto> closingDocument = stockOutInfoMapper.getClosingDocument(time);
        //领料出库弱管控标志位
        boolean downStockOutInfo = closingDocument.size() > 0;

        //销售发货
        List<PickingSaleDto> qPickingSale = pickingSaleMapper.getQClosingDocument(time);
        if (qPickingSale.size() > 0) {
            throw new GlobalException("存在需要审批的单据，不能进行结账");
        }
        //销售发货弱管控标志位
        List<PickingSaleDto> rPickingSale = pickingSaleMapper.getRClosingDocument(time);
        boolean downPickingSale = rPickingSale.size() > 0;

        //采购退货
        List<PickingPurchaseDto> qPickingPurchase = pickingPurchaseMapper.getQClosingDocument(time);
        if (qPickingPurchase.size() > 0) {
            throw new GlobalException("存在需要审批的单据，不能进行结账");
        }
        //采购退货弱管控标志位
        List<PickingPurchaseDto> rPickingPurchase = pickingPurchaseMapper.getRClosingDocument(time);
        boolean downPickingPurchase = rPickingPurchase.size() > 0;

        //其他出库(无审核)
        List<PickingRestDto> rPickingRest = pickingRestMapper.getRClosingDocument(time);
        boolean downPickingRest = rPickingRest.size() > 0;

        //库存盘点
        List<CheckListDto> qCheckList = checkManagementMapper.getQClosingDocument(time);
        if (qCheckList.size() > 0) {
            throw new GlobalException("存在需要审批的单据，不能进行结账");
        }
        //库存盘点弱管控标志位
        List<CheckListDto> rCheckList = checkManagementMapper.getRClosingDocument(time);
        boolean downCheckList = rCheckList.size() > 0;

        //调拨(无审核)
        List<AllotManagementDto> rAllotManagement = allotManagementMapper.getRClosingDocument(time);
        boolean downAllotManagement = rAllotManagement.size() > 0;

        //采购入库(无审核)
        List<PurchaseReceiptDto> rPurchaseReceipt = purchaseReceiptMapper.getRClosingDocument(time);
        boolean downPurchaseReceipt = rPurchaseReceipt.size() > 0;

        //销售退货
        List<SalesReturnDto> qSalesReturn = salesReturnMapper.getQClosingDocument(time);
        if (qSalesReturn.size() > 0) {
            throw new GlobalException("存在需要审批的单据，不能进行结账");
        }
        List<SalesReturnDto> rSalesReturn = salesReturnMapper.getRClosingDocument(time);
        boolean downSalesReturn = rSalesReturn.size() > 0;

        //完工入库(没有审核)
        List<WipCompletionDto> rWipCompletion = wipCompletionMapper.getRClosingDocument(time);
        boolean downWipCompletion = rWipCompletion.size() > 0;

        if (downStockOutInfo || downPickingSale || downPickingPurchase || downPickingRest || downCheckList || downAllotManagement
            || downPurchaseReceipt || downSalesReturn || downWipCompletion) {
            closingDocumentDto.setStatusCode("2001");
            closingDocumentDto.setResultMessage("存在未完成的单据，是否继续结账");
            return closingDocumentDto;
        } else {
            closingDocumentDto.setStatusCode("2002");
            return closingDocumentDto;
        }
    }

    /**
     * 入库打印
     *
     * @param warehousInspectionVo
     * @return
     * @throws Exception
     */
    @Override
    public boolean warehousInspection(WarehousInspectionVo warehousInspectionVo) throws Exception {
        PurchaseReceipt purchaseReceipt = purchaseReceiptMapper.selectById(warehousInspectionVo.getId());
        if (purchaseReceipt.getStatus() == 1 || purchaseReceipt.getStatus() == 2) {
            //修改状态为入库中
            purchaseReceipt.setStatus(2);
            purchaseReceipt.setMaterialUnit(warehousInspectionVo.getMaterialUnit());
            List<IncomingMaterialPrintingDetail> incomingMaterialPrintingDetails = new ArrayList<>();
            IncomingMaterialPrinting incomingMaterialPrinting = new IncomingMaterialPrinting();
            incomingMaterialPrinting.setDocumentType(purchaseReceipt.getDocumentType())
                .setDeptId(LoginHelper.getDeptId())
                .setReceiptNo(purchaseReceipt.getReceiptNo())
                .setSupplierCode(purchaseReceipt.getSupplierCode())
                .setQuantityBatch(warehousInspectionVo.getNumberCars())
                .setCreateBy(LoginHelper.getUsername())
                .setCreateTime(new Date())
                //唯一标识
                .setOnlyMark(remoteCodeService.splitList("IMP"))
                //生成批次号
                .setBatchNo(batchNoGenerate())
                .setMaterialCode(purchaseReceipt.getMaterialCode());
//                //如果是免检就保存打印状态为待打印，如果不是就保存待检验
//                if (warehousInspectionVo.getInspectionExemption() == 1) {
//                    incomingMaterialPrinting.setPrintStatus(2);
//                } else {
//                    incomingMaterialPrinting.setPrintStatus(1);
//                }
            incomingMaterialPrinting.setPrintStatus(2);
            incomingMaterialPrintingMapper.insert(incomingMaterialPrinting);
            //获取物料信息
            PublicMaterial publicMaterial = publicMaterialMapper.selectOne(new QueryWrapper<PublicMaterial>().lambda().eq(PublicMaterial::getMaterialCode, purchaseReceipt.getMaterialCode()));
            //存储打印明细数据
            for (int i = 0; i <= warehousInspectionVo.getNumberCars() - 1; i++) {
                IncomingMaterialPrintingDetail incomingMaterialPrintingDetail = new IncomingMaterialPrintingDetail();
                incomingMaterialPrintingDetail.setPrintId(incomingMaterialPrinting.getId())
                    .setBatchNo(incomingMaterialPrinting.getBatchNo())
                    .setReceiptQuantity(1)
                    .setMaterialCategory(purchaseReceipt.getMaterialCategory())
                    .setMaterialId(publicMaterial.getMaterialId())
                    .setMaterialCode(incomingMaterialPrinting.getMaterialCode())
                    .setMaterialNumber(remoteCodeService.splitList("CGRKDYNUM"))
                    .setMaterialUnit(warehousInspectionVo.getMaterialUnit())
                    .setReceiptId(purchaseReceipt.getId())
                    .setNetWeight(Double.parseDouble(warehousInspectionVo.getUnitContent()));
//                    //如果是免检就保存净重和毛重数据
//                    if (warehousInspectionVo.getInspectionExemption() == 1) {
//                        incomingMaterialPrintingDetail.setGrossWeight(entity.getNetWeight() / entity.getNumberCars());
//                        incomingMaterialPrintingDetail.setNetWeight(entity.getNetWeight() / entity.getNumberCars());
//                    } else {
//                        incomingMaterialPrintingDetail.setGrossWeight(entity.getNetWeight() / entity.getNumberCars());
//                    }
                incomingMaterialPrintingDetails.add(incomingMaterialPrintingDetail);
            }
            incomingMaterialPrintingDetailService.batchSave(incomingMaterialPrintingDetails);

            return purchaseReceiptMapper.updateById(purchaseReceipt) > 0;
        } else {
            throw new GlobalException("只能操作待入库的数据");
        }
    }


    /**
     * 批次号生成
     */
    public String batchNoGenerate() {
        String batchNo = "";
        String prefix = "CG";
        //查询缓存
        Object cacheObject = RedisUtils.getCacheObject(VariousKeyEnum.getValue(1));
        if (cacheObject == null) {
            String num = "001";
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            String format = sf.format(new Date());
            batchNo = prefix + format + num;
            //放入缓存
            RedisUtils.setCacheObject(VariousKeyEnum.getValue(1), num);
            return batchNo;
        }
        String s = cacheObject.toString();
        String s1 = addOne(s);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sf.format(new Date());
        batchNo = format + s1;
        //放入缓存
        RedisUtils.setCacheObject(VariousKeyEnum.getValue(1), s1);
        return batchNo;
    }

    /**
     * 字符串末尾加1
     */
    public String addOne(String testStr) {
        //根据不是数字的字符拆分字符串
        String[] strs = testStr.split("[^0-9]");
        //取出最后一组数字
        String numStr = strs[strs.length - 1];
        //如果最后一组没有数字(也就是不以数字结尾)，抛NumberFormatException异常
        if (numStr != null && numStr.length() > 0) {
            //取出字符串的长度
            int n = numStr.length();
            //将该数字加一
            int num = Integer.parseInt(numStr) + 1;
            String added = String.valueOf(num);
            n = Math.min(n, added.length());
            //拼接字符串
            return testStr.subSequence(0, testStr.length() - n) + added;
        } else {
            throw new NumberFormatException();
        }
    }
}
